我正在使用Python3.5并尝试从同一个网站上获取URL列表,代码如下:
import urllib.request
from bs4 import BeautifulSoup
url_list = ['URL1',
'URL2','URL3]
def soup():
for url in url_list:
sauce = urllib.request.urlopen(url)
for things in sauce:
soup_maker = BeautifulSoup(things, 'html.parser')
return soup_maker
# Scraping
def getPropNames():
for propName in soup.findAll('div', class_="property-cta"):
for h1 in propName.findAll('h1'):
print(h1.text)
def getPrice():
for price in soup.findAll('p', class_="room-price"):
print(price.text)
def getRoom():
for theRoom in soup.findAll('div', class_="featured-item-inner"):
for h5 in theRoom.findAll('h5'):
print(h5.text)
for soups in soup():
getPropNames()
getPrice()
getRoom()
到目前为止,如果我打印汤,获取propname,getPrice或getRoom,它们似乎可以工作。但我似乎无法让它遍历每个url并打印getPropNames、getPrice和getRoom。在
只学了几个月的Python所以非常感谢你的帮助!在
想想这条代码的作用:
我给你举个例子:
^{pr2}$url_list = ['one', 'two', 'three']
的输出是:你现在看到了吗?怎么回事?在
基本上,soup函数在第一个返回
return
-不要返回任何迭代器,任何列表;只有第一个BeautifulSoup
-这是iterable的幸运(或不幸运):)所以改变代码:
然后输出为:
但我相信这也行不通:)只是想知道sauce返回的是什么:
sauce = urllib.request.urlopen(url)
实际上你的代码在迭代什么:for things in sauce
-意味着things
是什么意思。在快乐的编码。在
每个
get*
函数都使用一个全局变量soup
,该变量在任何地方都没有正确设置。即使是这样,也不是一个好办法。将soup
改为函数参数,例如:第二,你应该从}来做{},把它变成一个生成器。否则,您需要返回
^{pr2}$soup()
而不是{BeautifulSoup
对象的列表。在我还建议使用XPath或CSS选择器来提取HTML元素:https://stackoverflow.com/a/11466033/2997179。在
相关问题 更多 >
编程相关推荐