【问题标题】:Unable to find correct href using Selenium/BS4无法使用 Selenium/BS4 找到正确的 href
【发布时间】:2021-11-12 07:08:48
【问题描述】:

我正在尝试使用以下代码简化我的财务数据收集。但是,它似乎有几个问题。我想抓取以下页面以获取特定的 href:'https://www.witan.com/investor-information/factsheets/#currentPage=1'

我试图解析的 href: href="/media/1767/witan-investment-trust_factsheet_310821.pdf"

目前我正在使用 selenium 来执行此操作,但是它有点慢,所以如果可以使用 BS4 进行抓取,我愿意提供建议 - 我的尝试到目前为止都失败了。

# Set options for selenium
options = Options()
options.headless = True
options.add_experimental_option('excludeSwitches', ['enable-logging'])
options.add_argument("--window-size=1920,1200")

# Requests website using Selenium & ChromeDriver
driver = webdriver.Chrome('C:/AnaConda/chromedriver.exe', options=options)
driver.get('https://www.witan.com/investor-information/factsheets/#currentPage=1') # Requests website
html = driver.page_source

soup = BeautifulSoup(html, "html.parser")
link_finder = soup.findAll('a', href=re.compile('/witan-investment-trust-factsheet'))[0]

当使用上面的代码时,我得到: class="ico-arrow document-view size" href="/media/1750/witan-investment-trust-factsheet-30jun2021.pdf" target="_blank"...

希望有人可以帮助我!

【问题讨论】:

    标签: selenium web-scraping beautifulsoup


    【解决方案1】:

    带有 PDF 链接的 HTML 文档通过 JavaScript 异步加载(因此beautifulsoup 在初始页面中看不到它们)。要打印所有 PDF 链接,您可以:

    import requests
    from bs4 import BeautifulSoup
    
    api_url = "https://www.witan.com/umbraco/surface/listing/DocumentListing"
    
    params = {
        "currentPage": "1",
        "year": "2021",
        "isArchive": "false",
        "pagination": "true",
    }
    
    with requests.session() as s:
        # load cookies:
        s.get("https://www.witan.com/investor-information/factsheets/")
        # get document page:
        soup = BeautifulSoup(s.get(api_url, params=params).content, "html.parser")
        for a in soup.select(".document-view"):
            print("https://www.witan.com" + a["href"])
    

    打印:

    https://www.witan.com/media/1767/witan-investment-trust_factsheet_310821.pdf
    https://www.witan.com/media/1763/witan-investment-trust_factsheet_310721.pdf
    https://www.witan.com/media/1750/witan-investment-trust-factsheet-30jun2021.pdf
    https://www.witan.com/media/1730/witan-investment-trust_factsheet_310521.pdf
    https://www.witan.com/media/1718/witan-factsheet-30apr2021.pdf
    

    【讨论】:

    • 嗨 Andrej,它似乎不再起作用了。这实际上每个月都会在他们放入新文档时发生,并且无法弄清楚原因。你有什么想法吗?
    猜你喜欢
    • 2016-08-13
    • 1970-01-01
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-07-02
    • 1970-01-01
    相关资源
    最近更新 更多