【问题标题】:Python BeautifulSoup only get 1 item from every pagePython BeautifulSoup 仅从每个页面中获取 1 项
【发布时间】:2017-08-16 08:26:38
【问题描述】:

我正在使用 BeautifulSoup 框架在 python 中开发网络爬虫。 我从目标页面获得了正确的信息。但它只从每个页面中获取 1 项。

我的代码如下:

import csv
import time
import bs4 as bs
from urllib.request import Request, urlopen

for i in range(1, 5):
   site = "XXURLXX".format(i)
   hdr = {'User-Agent': 'Mozilla/5.0'}
   req = Request(site, headers=hdr)
   page = urlopen(req)
   soup = bs.BeautifulSoup(page, 'html5lib')

data = []

for get_info in soup:
    name_box = soup.find('h2', attrs={'class': 'post-title'})
    name = name_box.text.strip()


    url_box = soup.find('a', attrs={'class': 'post-excerpt-download'})
    url = url_box.get('href')

data.append((name, url, site))

time.sleep(1)

print(data)

with open('stellarismods.csv', 'a') as csv_file:
    writer = csv.writer(csv_file)
    for url in data:
        writer.writerow([name, url, site])

我已经尝试过forloop

for name_box in soup.find('h2', attrs={'class': 'post-title'}):
       name = name_box.text.strip()


for url_box in soup.find('a', attrs={'class': 'post-excerpt-download'}):
    url = url_box.get('href')

但我仍然从每个页面中只得到 1 个项目。

【问题讨论】:

  • 第一个for 循环的意义何在?
  • 放一个你得到的html样本
  • find 返回第一个匹配元素,使用selectfind_all 然后迭代结果

标签: python beautifulsoup web-crawler


【解决方案1】:

试试find_all 函数。它将查找您要查找的所有元素。

【讨论】:

  • 感谢您的回复。但是当我这样做时,我收到以下错误:“AttributeError:ResultSet 对象没有属性'get'。您可能将项目列表视为单个项目。当您打算调用 find( )?”当我打印“url_box”时,我得到以下结果:“[Download, Download/a>]" 但是当我打印“url”时,我得到了上面的错误。
  • @J.Martin Functionfind() 返回字符串。函数find_all() 返回列表。你必须使用 for 循环。
猜你喜欢
  • 1970-01-01
  • 2021-10-13
  • 2020-07-26
  • 1970-01-01
  • 2019-10-24
  • 2019-07-18
  • 2017-09-14
  • 2013-06-21
  • 1970-01-01
相关资源
最近更新 更多