使用Python和Beautiful Soup进行Web抓取

时间:2017-03-16 17:43:51

标签: python web-scraping beautifulsoup

我正在练习构建网络刮刀。我现在正在进行的工作包括访问一个站点,抓取该站点上各个城市的链接,然后获取每个城市的所有链接,并抓取所述城市中所有属性的所有链接。

我正在使用以下代码:

import requests

from bs4 import BeautifulSoup

main_url = "http://www.chapter-living.com/"

# Getting individual cities url
re = requests.get(main_url)
soup = BeautifulSoup(re.text, "html.parser")
city_tags = soup.find_all('a', class_="nav-title")  # Bottom page not loaded dynamycally
cities_links = [main_url + tag["href"] for tag in city_tags.find_all("a")]  # Links to cities

如果我打印出city_tags,我会得到我想要的HTML。但是,当我打印cities_links时,我会AttributeError: 'ResultSet' object has no attribute 'find_all'

我在这里从其他q收集这个错误是因为city_tags没有返回,但是如果它打印出所需的html则不会出现这种情况?我注意到所说的html在[]中 - 这有什么不同吗?

2 个答案:

答案 0 :(得分:2)

好的city_tags是一个bs4.element.ResultSet(基本上是一个列表)标签,你在它上面调用find_all。您可能希望在结果集的每个元素中调用find_all,或者在此特定情况下只需检索其href属性

import requests
from bs4 import BeautifulSoup

main_url = "http://www.chapter-living.com/"

# Getting individual cities url
re = requests.get(main_url)
soup = BeautifulSoup(re.text, "html.parser")
city_tags = soup.find_all('a', class_="nav-title")  # Bottom page not loaded dynamycally
cities_links = [main_url + tag["href"] for tag in city_tags]  # Links to cities

答案 1 :(得分:1)

如错误所示, city_tags 是一个ResultSet,它是一个节点列表,它没有find_all方法,你要么必须遍历集合并在每个单独的节点上应用find_all,或者在您的情况下,我认为您只需从每个节点中提取href属性:

[tag['href'] for tag in city_tags]

#['https://www.chapter-living.com/blog/',
# 'https://www.chapter-living.com/testimonials/',
# 'https://www.chapter-living.com/events/']
相关问题