python - 网页美化 html带bs4
问题描述
我正在为自己构建一个网络爬虫,以从路透社获取财务数据和新闻。到目前为止,它就像一个魅力,除了时间/日期。示例:在 https://www.reuters.com/companies/WDIG.DE/profile 上有一个像这样的事件框:
日期“2020 年 4 月 30 日”包含在源中,如下所示:
<time class="TextLabel__text-label___3oCVw TextLabel__white___32MyF TextLabel__regular___2X0ym EventLabel-date-4_Sun">Apr 30, 2020</time>
但
result = requests.get(site)
soup = bs.BeautifulSoup(result.text, 'lxml')
soup.find('time', {'class': 'TextLabel__text-label___3oCVw TextLabel__white___32MyF TextLabel__regular___2X0ym EventLabel-date-4_Sun'}).text
什么都不返回,即我想要的数据(2020 年 4 月 30 日)不在我从我的请求中得到的响应中。任何人都知道如何使这项工作?
解决方案
这里有 2 个代码片段,第一个是您所做的。
片段1:
import requests
import bs4
site = "https://www.reuters.com/companies/WDIG.DE/profile"
result = requests.get(site)
soup = bs4.BeautifulSoup(result.text, 'lxml')
with open('soup_1.txt', 'w', encoding='utf8') as f:
f.write(soup.prettify())
print(soup.find('time', {'class': 'TextLabel__text-label___3oCVw TextLabel__white___32MyF TextLabel__regular___2X0ym EventLabel-date-4_Sun'}).text)
输出:
<time class="TextLabel__text-label___3oCVw TextLabel__white___32MyF TextLabel__regular___2X0ym EventLabel-date-4_Sun"></time>
片段 2:
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--headless")
driver = webdriver.Chrome(options=chrome_options)
driver.set_page_load_timeout(40)
driver.get(site)
soup = bs4.BeautifulSoup(driver.page_source, "html.parser")
with open('soup_2.txt', 'w', encoding='utf8') as f:
f.write(soup.prettify())
driver.quit()
print("done")
输出:
<time class="TextLabel__text-label___3oCVw TextLabel__white___32MyF TextLabel__regular___2X0ym EventLabel-date-4_Sun">Apr 30, 2020</time>
要使selenium 正常工作,您需要下载chromedriver并确保它与您的脚本位于同一位置。
推荐阅读
- r - Rvest 网页抓取如何获取下一页
- python - 使用 python 2.7 构建 Conda noarch 包
- arrays - 如何在反应中使用 jest 编写单元测试用例?
- python - 如何在 python 2.7 中处理 Unicode 问题而不忽略
- flutter - Flutter 是否可以在不创建新状态的情况下推送已经初始化的页面?
- sql - 转换行中的列名
- ajax - 为什么 Symfony4 在这个 ajax 请求上给匿名用户?
- cordova - Cordova 插件 - 安装特定平台的最后可用版本
- javascript - AmplifyJS 状态错误类型错误:无法读取未定义的属性“状态”
- angular - 更改路由物料表时闪烁