【问题标题】:using beautifulsoup to scrape html error "div" not defined使用 beautifulsoup 抓取 html 错误“div”未定义
【发布时间】:2017-06-17 15:41:05
【问题描述】:

我正在尝试提取 div 类下的信息,但是当我使用代码时,消息显示“div”未定义。汤很好用,而且我看到里面有很多 div,可能是什么问题?

soup = BeautifulSoup(html, "html.parser")
for item in soup.find_all("div", attrs={"class" : "article-content"}):
        print(div.find("a")['href'])

【问题讨论】:

    标签: python beautifulsoup


    【解决方案1】:

    div 变量实际上从未定义,您的意思是使用 item 代替:

    for item in soup.find_all("div", attrs={"class" : "article-content"}):
        print(item.find("a")['href'])  # or item.a['href']
    

    或者,您可以通过CSS selector 直接访问链接:

    for a in soup.select("div.article-content a"):
        print(a['href'])
    

    【讨论】:

    • 谢谢!我实际上是盯着它看了几分钟后才想到的,是的,现在我明白它应该是 div 而不是 item
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-03-24
    • 2019-04-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-11-14
    • 1970-01-01
    相关资源
    最近更新 更多