gpt4 book ai didi

Python:打印文本元素不起作用

转载 作者:太空宇宙 更新时间:2023-11-03 18:00:59 25 4
gpt4 key购买 nike

我正在尝试使用 python 学习抓取,并且 python 的新用户只是按照在线教程学习。如视频所示,打印命令不起作用。下面是完整的代码。

import requests
from bs4 import BeautifulSoup

url = "http://www.yellowpages.com/search?search_terms=coffee&geo_location_terms=Los+Angeles%2C+CA"

r = requests.get(url)

soup = BeautifulSoup(r.content)

g_data = soup.find_all("div", {"class": "info"})
for item in g_data:
print (item.text)

for item in g_data:
print (item.contents[0].text)
print (item.contents[1].text)

#Print text elements (**The command below does not work!!!!**)
for item in g_data:
print (item.contents.find_all("a", {"class": "business-name"}).text)

最佳答案

解析嵌套html使用 BeautifulSoup 需要一些练习,但是一旦您了解了它的工作原理,一切都会非常整洁。

有许多小缺陷会阻止您的代码正常工作。我不会假装考虑到所有这些,但我们可以从一个逐步的示例开始,希望这能让您更好地理解。

例如,您不能这样做:

item.contents.find_all("a")

因为item.contents不是 BeautifulSoup 对象。这是一个基本的Python list BeautifulSoup 在 item 中发现的内容。为了继续在item中搜索,您必须使用 find_all 查询对象本身。因此,您可以这样做:

for item in g_data:
print(item.find_all("a", {"class": "business-name"}).text)

但它仍然不正确。因为两件事:

  1. find_all 的结果是 listobjects ,其中没有 text方法
  2. 无论如何,BeautifulSoup 对象没有 text方法。但他们有一个contents方法

这个contents方法返回在标签内找到的字符串列表。因此,您必须执行以下操作:

for item in g_data:
links = item.find_all("a", {"class": "business-name"})
links_contents = [ link.contents[0] for link in links ]
print("\n".join(links_contents))

如果其余部分正确(我不确定),上面的代码会给你类似的东西:

Content of my first link in the first item
Content of my second link in the first item
Content of my first link in the second item
Content of my second link in the second item
... and so forth

关于Python:打印文本元素不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27677769/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com