【问题标题】:Not Getting Expected find results with BeautifulSoup使用 BeautifulSoup 没有得到预期的查找结果
【发布时间】:2021-09-29 10:22:59
【问题描述】:

您好,我正在尝试在 stackoverflow 页面上回答所有问题

为此,我正在尝试以下代码,但没有打印任何内容我可以在这里纠正什么吗?

from bs4 import BeautifulSoup
import requests

content = requests.get("https://stackoverflow.com/").content

soup = BeautifulSoup(content, features="html.parser")


for i in soup.find_all("a", class_="question-hyperlink", href=True):
    print(i)

【问题讨论】:

    标签: python python-3.x web-scraping


    【解决方案1】:

    您应该考虑使用它来获取所有链接:

    from bs4 import BeautifulSoup
    import requests
    
    content = requests.get("https://stackoverflow.com/").content
    
    soup = BeautifulSoup(content, features="html.parser")
    
    links = [a['href'] for a in soup.find_all('a', href=True)]
    print(links)
    

    为了能够按类进行搜索,您应该使用这个:

    from bs4 import BeautifulSoup
    import requests
    
    content = requests.get("https://stackoverflow.com/").content
    
    soup = BeautifulSoup(content, features="html.parser")
    
    links = [a['href'] for a in soup.find_all('a', class_="question-hyperlink", href=True)]
    print(links)
    

    但是,在运行脚本后,我打印了一个空列表,这意味着它在给定的类中找不到任何链接。

    【讨论】:

    • 感谢您的回答,但这无济于事,我只需要打印问题,因此使用您的方法搜索类,所有标签都会打印出来
    • 我刚刚编辑了我的答案。这应该可以解决您的问题;)
    • 但如果我尝试检查 STO 上的任何问题,我可以清楚地看到类、文本、href 存在
    • 这可能是因为您尝试访问的类位于您需要首先访问的其他类或元素中。
    猜你喜欢
    • 1970-01-01
    • 2022-01-24
    • 2021-12-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多