带bs4,python,web-scraping,beautifulsoup"/>

首页 > 解决方案 > 网页美化 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 日)不在我从我的请求中得到的响应中。任何人都知道如何使这项工作?

标签: pythonweb-scrapingbeautifulsoup

解决方案


这里有 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并确保它与您的脚本位于同一位置。


推荐阅读