我的目标是从这个页面中提取所有的href链接并找到.pdf链接.我试着使用requests库和Selenium,但它们都不能提取它.

如何解决这个问题?谢谢

例如:这包含一个.pdf文件链接

enter image description here

This is the request code:

    import requests
    from bs4 import BeautifulSoup

    headers = {'User-Agent': 'Mozilla/5.0 (X11; Ubuntu; Linux x86_64; rv:109.0) Gecko/20100101 Firefox/113.0'}
    url="https://www.bain.com/insights/topics/energy-and-natural-resources-report/"
    
    response = requests.get(url, headers=headers)
    soup = BeautifulSoup(response.text, 'html.parser')

    for link in soup.find_all('a'):
        print(link.get('href'))

This is the selenium code:

    from selenium import webdriver
    from selenium.webdriver.chrome.service import Service as ChromeService
    from webdriver_manager.chrome import ChromeDriverManager
    from bs4 import BeautifulSoup

    options = webdriver.ChromeOptions()
    driver = webdriver.Chrome(service=ChromeService(ChromeDriverManager().install()), options=options)

    page_source = driver.get("https://www.bain.com/insights/topics/energy-and-natural-resource-report/")
    driver.implicitly_wait(10)

    soup = BeautifulSoup(page_source, 'html.parser')
    for link in soup.find_all('a'):
        print(link.get('href'))

    driver.quit()

推荐答案

Here is the version how to get all pdfs from that page:

import json
import re

import requests
from bs4 import BeautifulSoup


def find_pdfs(data):
    if isinstance(data, dict):
        for k, v in data.items():
            if k == "url" and ".pdf" in v:
                yield v
            else:
                yield from find_pdfs(v)
    elif isinstance(data, list):
        for v in data:
            yield from find_pdfs(v)


url = "https://www.bain.com/insights/topics/energy-and-natural-resources-report/"

soup = BeautifulSoup(requests.get(url).content, "html.parser")
iframe_src = soup.iframe["src"]
iframe_text = requests.get(iframe_src).text

doc = re.search(r"docVersion: (.*}),", iframe_text).group(1)
doc = json.loads(doc)

data = requests.get(doc["committedJsonUrl"]).text
data = re.search(r"(\{.*\})\);", data).group(1)
data = json.loads(data)

# print(json.dumps(data, indent=4))
pdfs = set(find_pdfs(data))
print(*pdfs, sep="\n")

打印:

https://www.bain.com/globalassets/noindex/2022/bain_report_global-private-equity-report-2022.pdf
https://www.bain.com/globalassets/noindex/2023/bain_report_engineering_and_r_and_d_report_2023.pdf
https://www.bain.com/globalassets/noindex/2023/bain_report_energy_and_natural_resources_2023.pdf

Python相关问答推荐

Odoo -无法比较使用@api.depends设置计算字段的日期

仅从风格中获取 colored颜色 循环

提取两行之间的标题的常规表达

在内部列表上滚动窗口

Python多处理:当我在一个巨大的pandas数据框架上启动许多进程时,程序就会陷入困境

如何使用Python将工作表从一个Excel工作簿复制粘贴到另一个工作簿?

max_of_three使用First_select、second_select、

PywinAuto在Windows 11上引发了Memory错误,但在Windows 10上未引发

从收件箱中的列中删除html格式

修复mypy错误-赋值中的类型不兼容(表达式具有类型xxx,变量具有类型yyy)

对所有子图应用相同的轴格式

如何创建一个缓冲区周围的一行与manim?

python中字符串的条件替换

合并帧,但不按合并键排序

交替字符串位置的正则表达式

并行编程:同步进程

如何过滤组s最大和最小行使用`transform`'

修改.pdb文件中的值并另存为新的

正在try 让Python读取特定的CSV文件

查找数据帧的给定列中是否存在特定值