python - Python for循环没有遍历所有元素
问题描述
我正在尝试编写我第一次webscraper
使用python
and的代码BeautifulSoup
。
我正在尝试检索网页上所有列表的所有 URL,但我没有得到一个包含所有 URL 的数组,而是只得到一个 URL。
以下是我使用的代码
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.pararius.com/apartments/enschede'
uClient = uReq(my_url)
page_html=uClient.read()
uClient.close()
page_soup = soup(page_html,"html.parser")
compartments = page_soup.findAll("li",{"class":"property-list-item-container"})
#Here is where im trying to store all the urls in url_det
for compartment in compartments:
url_det = compartment.h2.a["href"]
任何输入表示赞赏!
解决方案
循环的每次迭代都会覆盖 的内容url_det
,而是使用列表推导来存储列表中的所有值,例如:
from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
my_url = 'https://www.pararius.com/apartments/enschede'
uClient = uReq(my_url)
page_html=uClient.read()
uClient.close()
page_soup = soup(page_html,"html.parser")
compartments = page_soup.findAll("li",{"class":"property-list-item-container"})
url_det = [compartment.h2.a["href"] for compartment in compartments]
print(url_det)
>>> ['/house-for-rent/enschede/PR0001596564/otto-van-taverenstraat', ... , '/house-for-rent/enschede/PR0001594320/hanenberglanden']
推荐阅读
- shell - 使用 shell 脚本调用 tibco soap webservice
- python - 我可以在不依赖未来包的情况下运行 futurize --stage2 更改吗
- python - 有没有比“for”更快的方法来比较列中的值来选择我想要的值?
- python - 无法在pycharm中安装curses包[找不到满足curses-win要求的版本(来自版本:无)]
- javascript - 您可以按数组值的字母顺序对对象进行排序吗?
- java - 使用 lombok 生成 param 接受附加参数的构造函数
- java - 使用 Google Admob 自动滚动片段和活动?
- css - 在原始 CSS 上使用正则表达式提取 DOM 元素数据
- redux - 处理可空类型时出现流错误
- here-olp - 是否可以检查版本化目录图层的早期版本?