【问题标题】:How to use Selenium+BeautifulSoup to get data from dynamically created elements如何使用 Selenium+BeautifulSoup 从动态创建的元素中获取数据
【发布时间】:2020-04-02 22:46:18
【问题描述】:

关于 StackOverFlow 的第一个问题。我正在尝试网络抓取fxstreet.com/news。似乎他们的新闻提要正在动态生成文章。 BeautifulSoup 无法收集这些信息,所以我决定使用 Selenium。但是,我无法使用 Selenium 访问显示的文章。

import requests
from bs4 import BeautifulSoup
import re
from selenium import webdriver
from webdriver_manager.chrome import ChromeDriverManager
driver = webdriver.Chrome(ChromeDriverManager().install())
driver.get('https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0')

article = driver.find_element_by_link_text('/news')
for post in article:
    print(post.text)

我想制作一个定期检查新文章的爬虫,这些文章的 URL 为:https://www.fxstreet.com/news...(endpoint)

但是,当我尝试查找 hrefs/'a' 标签时,我会在整个网站上获得许多链接,但它们都不是实时提要中的新闻文章。当我查找每个“div”时,我会为我准备好整个 html:

                    <article class="fxs_entriesList_article_with_image ">
                    <h3 class="fxs_entryHeadline">
                        <a href="https://www.fxstreet.com/news/gbp-usd-upside-potential-limited-in-covid-19-uncertainties-202004021808" title="GBP/USD upside potential limited in COVID-19 uncertainties">GBP/USD upside potential limited in COVID-19 uncertainties</a>
                    </h3>
                    <address class="fxs_entry_metaInfo">
                        <span class="fxs_article_author">
                            By <a href="/author/ross-j-burland" rel="nofollow">Ross J Burland</a>
                        </span> | <time pubdate="" datetime="">18:08 GMT</time>
                    </address>
                </article>

告诉我它以某种方式存在于某个地方,但我完全无法与之互动。那么,当 Selenium 无法搜索“a”标签或部分链接时,如何访问我需要的链接?我还尝试使用以下方法查找确切的链接:

elem = driver.find_elements_partial_link("news")

for element in elem:
       print(element.get_attribute("innerHTML"))

无济于事。我也尝试过显式和隐式等待。谢谢。

【问题讨论】:

    标签: python selenium web-scraping


    【解决方案1】:

    请使用下面的 css 获取所有新闻相关链接。

    h4.fxs_headline_tiny a
    

    显式等待需要额外的导入。

    from selenium.webdriver.support.ui import WebDriverWait
    from selenium.webdriver.common.by import By
    from selenium.webdriver.support import expected_conditions as EC
    

    您的代码应如下所示。

    url = "https://www.fxstreet.com/news?q=&hPP=17&idx=FxsIndexPro&p=0"
    driver.get(url)
    WebDriverWait(driver,120).until(EC.presence_of_element_located((By.CSS_SELECTOR,"h4.fxs_headline_tiny a")))
    news_elems = driver.find_elements_by_css_selector("h4.fxs_headline_tiny a")
    for ele in news_elems:
        print(ele.get_attribute('href'))
    

    【讨论】:

    • 如果您认为问题已解决,请在我的回答中勾选左侧的复选标记,选择Accept回答。
    • 抱歉,Stackoverflow 的新手。完成!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-04-21
    • 2021-09-09
    • 2021-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多