【问题标题】:Can't seem to extract text from element using BS4似乎无法使用 BS4 从元素中提取文本
【发布时间】:2018-12-22 13:46:40
【问题描述】:

我正在尝试提取此网页上的名称:https://steamcommunity.com/market/listings/730/AK-47%20%7C%20Redline%20%28Field-Tested%29

我试图从中获取它的元素是

<h1 class="hover_item_name" id="largeiteminfo_item_name" style="color: 
rgb(210, 210, 210);">AK-47 | Redline</h1>

我可以使用 selenium 搜索 ID“largeiteminfo_item_name”并以这种方式检索文本,但是当我使用 bs4 复制时,我似乎找不到文本。

我尝试搜索类“item_desc_description”,但也找不到任何文本。我做错了什么?

a = soup.find("h1", {"id": "largeiteminfo_item_name"})
a.get_text()

a = soup.find('div', {'class': 'item_desc_description'})
a.get_text()

我期待“AK-47 | Redline”,但第一次尝试收到 '' 和 '\n\n\n\n\n\n\n\n\n\n\n\n\n\n \n\n' 第二次尝试。

【问题讨论】:

    标签: html python-3.x beautifulsoup


    【解决方案1】:

    您尝试提取的数据不在 HTML 页面中,我猜它可能是用 JavaScript 生成的(只是猜测)。

    但是我设法在 div“market_listing_nav”中找到了信息。

    from bs4 import BeautifulSoup as bs4
    import requests
    
    lnk = "https://steamcommunity.com/market/listings/730/AK-47%20%7C%20Redline%20%28Field-Tested%29"
    res = requests.get(lnk)
    
    soup = bs4(res.text, features="html.parser")
    elem = soup.find("div", {"class" : "market_listing_nav"})
    
    print(elem.get_text())
    

    这将输出以下内容

    Counter-Strike: Global Offensive
                        >
                                            AK-47 | Redline (Field-Tested)
    

    查看网页源代码以获取格式更好的标签,或者只是清理我的代码生成的标签。

    【讨论】:

    • 嘿,谢谢伙计,给我几分钟让我实现这个,然后我会接受它。我感谢您的帮助。我想这确实有道理,这个网站的一些运行在 iframe 上,我想知道是否可能是这种情况。感谢您的帮助,请尽快谈
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 1970-01-01
    • 2021-02-03
    相关资源
    最近更新 更多