首页 > 解决方案 > 使用 BeautifulSoup4 获得结果的问题

问题描述

我正在学习网络解析,并使用 BS4 创建了一个 python 脚本。当我尝试运行此脚本时,我只获得 1 项的输入。

import requests
from bs4 import BeautifulSoup as BS
url = 'https://www.gumtree.com.au/s-sydney/computer/k0l3003435?price-type=free'
headers = {'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:82.0)'}
response = requests.get(url, headers=headers)
response.content
soup = BS(response.content, 'html.parser')
items_list = soup.find_all('section', {'class': 'search-results-page__user-ad-collection'})
for items in items_list:
    title = items.find('span', {'class': 'user-ad-row-new-design__title-span'}).text
    url_tag = items.find('a', {'href': 'user-ad-row-new-design.link--base-color-inherit.link--hover-color-none.link--no-underline'})
    url = url_tag.text if url_tag else "n/a"
print('item:', title, '\nlink:', url)

出于某种原因,我只得到一个项目的结果?

item: PC Joysticks 
link: n/a

谁能帮帮我。

注意:这是我第一次在这里发帖,所以提前道歉。

标签: pythonwindowsbeautifulsoupautomationhtml-parsing

解决方案


看起来像缩进的问题。在 for 循环中推送最后一个打印行:

for items in items_list:
    title = items.find('span', {'class': 'user-ad-row-new-design__title-span'}).text
    url_tag = items.find('a', {'href': 'user-ad-row-new-design.link--base-color-inherit.link--hover-color-none.link--no-underline'})
    url = url_tag.text if url_tag else "n/a"
    print('item:', title, '\nlink:', url)

推荐阅读