我将 bs4 与 python 一起使用,并尝试从网页中获取数据。 Link我在我想要的信息上使用了检查元素,但两者都有相同的标签、类。
<a class="cell__value" data-tracker-action="click" data-tracker-label="information_technology.01" href="/markets/sectors/information-technology">
Information Technology
</a>
</div>
<div class="cell__return">
<div class="cell__label">
% Price Change
</div>
<div class="cell__value" data-type="better">
+0.05%
</div>
</div>
</div>
<div class="cell">
<div class="cell__name">
<div class="cell__label">
Industry
</div>
<a class="cell__value" data-tracker-action="click" data-tracker-label="information_technology.02" href="/markets/sectors/information-technology">
Software & Services
</a>
</div>
<div class="cell__return">
<div class="cell__label">
% Price Change
</div>
<div class="cell__value" data-type="worse">
-0.04%
</div>
</div>
</div>
</div>
我是这样做的:
sect= soup.find("a",{"data-tracker-label":"information_technology.01"})
print sect.text
sect_per= soup.find("div",{"data-type":"worse"or"better"})
print sect_per.text
ind=soup.find("a",{"data-tracker-label":"information_technology.02"})
print ind.text
ind_per=soup.find("div",{"div",{"data-type":"worse"or"better"})
print ind_per
两者 print ind_per 和 print ind_per 都给我相同的结果,因为相同的类和标记
我需要分别提取 +0.05% 和 -0.04% 。
请建议我这样做的方法。
请您参考如下方法:
soup = BeautifulSoup(example, "html.parser")
for cell in soup.find_all("div", class_="cell"):
name = ""
namecell = cell.find("a", class_="cell__value", text=True)
if namecell is not None:
name = namecell.get_text(strip=True)
price_chage = cell.find("div", class_="cell__value").get_text(strip=True)
print ( "%s: Price Change: %s" % (name, price_chage))
哪些输出:
Information Technology: Price Change: +0.05%
Software & Services: Price Change: -0.04%
您可以保存该值以供进一步处理。
