【问题标题】:BeautifulSoup: How to extract tag values?BeautifulSoup:如何提取标签值?
【发布时间】:2018-04-23 23:27:56
【问题描述】:

我对编程很陌生,似乎无法解决以下数据提取问题。

这是我的数据的样子(黄色 = 我要提取的内容):

View image

提取标题、价格和时间可以正常工作:

# Title
advertTitle = firstAdvert.find_all(
"section", {"class": "aditem-main"})[0].find("h2").text.encode("utf-8").strip().replace("\n", "")

# Price
advertPrice = firstAdvert.find_all(
"section", {"class": "aditem-details"})[0].find("strong").text.encode("utf-8").strip().replace("\n", "")

# Time
advertTimeAdded = advertTitle = firstAdvert.find_all(
"section", {"class": "aditem-addon"})[0].text.encode("utf-8").strip().replace("\n", "")

但我的主要问题是:如何从中提取“79924470”:

<article class="aditem" data-adid="79924470">

我已经尝试过例如:

item.find_all("article", "data-adid"}

感谢您为我指明正确的方向!

【问题讨论】:

  • 请不要在图片中发布代码。有些可能无法打开,从而使他们无法提供帮助。 -1

标签: python beautifulsoup web-crawler


【解决方案1】:

由于您使用的是 BeautifulSoup,因此您可以这样做来提取属性的值:

soup = BeautifulSoup(file, "lxml")
print soup.article['data-adid'] # output : 79924470

【讨论】:

    【解决方案2】:

    可以使用一系列选择来获取各种元素,如下所示:

    from bs4 import BeautifulSoup
    
    soup = BeautifulSoup(html, "lxml")
    print soup.article['data-adid']
    image = soup.select('div.imagebox.srpimagebox')[0]
    print image['data-href']
    print image['data-imgsrc']
    print soup.select('section h2 a')[0].text
    print ', '.join([v.strip() for v in soup.select('section.aditem-details')[0].text.strip().split('\n')])
    print soup.select('section.aditem-addon')[0].get_text(strip=True)
    

    其中显示:

    79924470
    /ref/79924470
    https://imgserver.com/012004.JPG
    I am a title
    12.380€, 50111, Cityname, 25km
    Today, 16:19
    

    【讨论】:

    • 哇,这太有用了!非常感谢马丁。
    【解决方案3】:

    你可以这样做:

    data = []
    for element in soup.find_all({'data-adid':'79924470'}):
        data.append(element['data-adid']
    

    这应该将data-adid 的每个值添加到列表data

    【讨论】:

    • 我应该解释得更好。数字“79924470”每次都不一样。所以我有一个包含“
      ”的列表,我试图只提取数字。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-12-05
    • 2021-12-22
    • 1970-01-01
    • 2013-04-29
    • 1970-01-01
    • 1970-01-01
    • 2020-01-07
    相关资源
    最近更新 更多