python - 使用 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
谁能帮帮我。
注意:这是我第一次在这里发帖,所以提前道歉。
解决方案
看起来像缩进的问题。在 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)
推荐阅读
- php - Codeigniter 使用库或助手使发送电子邮件干燥?
- reactjs - MobX 不会在 fetch promise 回调中更新 react DOM
- python - 从单独的文件(Python)连接到 SQLite 内存数据库
- c++ - 将共享指针插入到该对象集时,不调用类重载运算符“<”
- javascript - 如何使用拖动事件从元素的所有子元素中删除指针事件?
- css - 仅使用 CSS 隐藏 Firefox 和 Internet 探索中的滚动条?
- css - 如何同时向标签添加多个 CSS 属性?
- ios - Firebase / Firestore上的多次查询
- firebase - Firestore 规则中的 WriteFields 仅适用于模拟器
- java - 尽管设置了代码页和 outputEncoding,但使用 Powershell 3 返回问号的 Java 代码执行命令。