Python + BeautifulSoup:无法从特定网站找到联系页面

问题描述 投票:0回答:1

我尝试使用Python和BeautifulSoup库从不同的网站找到联系页面。我使用的逻辑是查找包含关键工作“contact”的不同变体的标签,并尝试使用此逻辑从那里提取链接

contact_links = soup.find_all('a', text=re.compile(r'(contact|kontakt)', re.IGNORECASE))

contact_links = soup.find_all('a', href=re.compile(r'(contact|kontact)', re.IGNORECASE))

虽然它适用于很多情况,但也有一些地方找不到页面,其中一个例子就是这个网站:https://www.teleflex.com/usa/en/

你知道为什么它不起作用吗?

编辑:

我发现可以使用 Selenium,添加以下内容:

browser = webdriver.Chrome()
browser.get(url)
html_content = browser.page_source
print(html_content)
soup_1 = BeautifulSoup(html_content, "html.parser")
contact_links_1 = soup_1.find_all('a', text=re.compile(r'(contact|kontakt)', re.IGNORECASE))

虽然我能够实际找到一个网址,但它似乎并不总是有效,因为 findAll 方法找不到此元素:

<a title="Contact form" href="https://reigjofre.com/en/contact/">Contact form

来自我使用的 htmlContent 变量。

python web-scraping beautifulsoup
1个回答
0
投票

它不起作用,因为页面正在执行来自 Javascript 的额外请求来加载页眉/页脚。要获取链接,您可以使用:

import re

import requests
from bs4 import BeautifulSoup

urls = [
    "https://www.teleflex.com/usa/en/includes/USA_EN_header.html",
    "https://www.teleflex.com/usa/en/includes/USA_EN_footer.html",
]

for u in urls:
    soup = BeautifulSoup(requests.get(u).content, "html.parser")
    contact_links = soup.find_all(
        "a", href=re.compile(r"(contact|kontact)", re.IGNORECASE)
    )
    print(contact_links)

打印:

[<a class="" href="/usa/en/contact/north-america/">Contact</a>]
[<a class="" href="/sea/en/contact/asia-pacific/">Asia Pacific</a>, <a class="" href="/usa/en/contact/north-america/index.html">CONTACT</a>]
© www.soinside.com 2019 - 2024. All rights reserved.