如何提取标签值?

2024-09-27 21:29:32 发布

您现在位置:Python中文网/ 问答频道 /正文

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

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

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”:

^{pr2}$

我试过这样的例子:

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

谢谢你给我指出了正确的方向!在


Tags: 数据text编程sectionallfindreplaceutf
3条回答

你可以这样做:

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

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

由于使用的是BeautifulSoup,因此可以执行以下操作来提取属性的值:

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

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

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)

显示:

^{pr2}$

相关问题 更多 >

    热门问题