python-3.x - 如何通过其 CSS 选择器字符串选择此元素?
问题描述
从这个urlhttps://www.collinsdictionary.com/dictionary/french-english/conjugation/aimer
,我试图提取链接
<a class="link-right verbtable" href="https://www.collinsdictionary.com/dictionary/french-english/conjugation/aimer">Full verb table</a>
其 CSS 选择器是div.content.definitions.dictionary.biling > div.hom > span > span.xr > a
. 我按照书中的说明用 Python 自动化无聊的东西
from bs4 import BeautifulSoup
url = 'https://www.collinsdictionary.com/dictionary/french-english/aimer'
soup = BeautifulSoup(url, 'html.parser')
soup.select('div.content.definitions.dictionary.biling > div.hom > span > span.xr > a')
您能否详细说明结果如何[]
?
解决方案
这是因为柯林斯词典使用 Cloudfare 来提高其网站和服务的安全性和性能。因此,当您向其服务器请求时。它不会给你 HTML 文件。
<title>Access denied | www.collinsdictionary.com used Cloudflare to restrict access</title>
为了通过它的安全。您必须在请求中设置用户代理。
from bs4 import BeautifulSoup
import requests
user_agent = {'User-agent': "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36"}
url = 'https://www.collinsdictionary.com/dictionary/french-english/aimer'
doc = requests.get(url, headers = user_agent).text
soup = BeautifulSoup(doc, 'html.parser')
result = soup.select('div.content.definitions.dictionary.biling > div.hom > span > span.xr > a')
print(result)
这将为您提供结果:
[<a class="link-right verbtable" href="https://www.collinsdictionary.com/dictionary/french-english/conjugation/aimer">Full verb table</a>]
推荐阅读
- python - 如何在运行 Jenkins CI 管道时屏蔽作为用户输入传递的密码?
- node.js - 如何使用对话流实现获取设备精确位置
- r - R ggplot2:尽管位置= position_dodge(0.9),但标签不在geom_bar上的躲避位置
- javascript - 平滑滚动不适用于动画鼠标向下滚动按钮
- c# - 如何区分 lambda 表达式中的鼠标按钮
- javascript - 在单个任务中异步运行 gulp 方法
- c++ - 两个二项式系数模 10^9 + 7 的 GCD
- php - kubernetes php nginx 部署分享量
- kubernetes - Helm 存储库在使用 Jenkins 和 Kubernetes 的 CI/CD 管道中的作用
- .net - 为什么这个对象的唯一引用设置为空后,它没有变成垃圾?