如何将 2 个网络抓取列表合并为一个



我尝试将 2 个网络抓取列表合并到一个列表中,但它所做的只是显示一个实例。(我已经有了名字列表和地址列表,我只想加入他们(。

from bs4 import BeautifulSoup
import urllib.request
def get_HTML(url):
response = urllib.request.urlopen(url)
html = response.read()
return html

第一个列表:

venues_html = get_HTML('http://www.cxra.com/venues/new-york/')
soup = BeautifulSoup(venues_html, "lxml")
for venue in soup('a', attrs={'href' : '#', 'onclick' : 'return false;'}):
display (venue.text)

输出:

'Manhattan Center Studios'
'Ellis Island'
'The TimesCenter'
'The Altman Building'
'NYIT Auditorium on Broadway'

第二个列表

for info in soup.findAll('div', attrs={'class' : 'infoUnit col-md-6'}):
display (info.text)

输出:

'n n311 West 34th StreetrnNew York City, 94710nn212.613.5536n'
'n nEllis IslandrnNew York, NY 10004nn212.613.5535n'
'n n242 W 41st StrnNew York, NY 10036nn212.613.5535n'
'n n135 W 18th StrnNew York, NY 10011nn212.613.5535n'
'n n1871 BroadwayrnNew York, NY 10023nn212.613.5536n'

尝试将两者结合起来:

print ("Venue: " + venue.text + info.text)

输出:

Venue: NYIT Auditorium on Broadway
1871 Broadway
New York, NY 10023
212.613.5536

我希望它对所有不同的场地都这样做,而不仅仅是一个。我尝试过循环,但它们似乎只是反复显示一个实例。

在不知道 display(( 到底是什么的情况下,我的猜测是你没有打印所有的"实例",因为你只从两个 for 循环的最后一次迭代中获得结果。

在不进行结构更改的情况下,最快的方法是将两个 bs4 废料的输出保存到两个列表中,并使用循环显示其内容。

from bs4 import BeautifulSoup
import urllib.request
import sys
def get_HTML(url):
response = urllib.request.urlopen(url)
html = response.read()
return html
venues_html = get_HTML('http://www.cxra.com/venues/new-york/')
soup = BeautifulSoup(venues_html, "lxml")
print('data scrapped')
list1 = []
list2 = []
for venue in soup('a', attrs={'href' : '#', 'onclick' : 'return false;'}):
list1.append(venue.text)
for info in soup.findAll('div', attrs={'class' : 'infoUnit col-md-6'}):
list2.append(info.text)
if len(list1) != len(list2):
print('Two lists not aligned, aborting')
sys.exit(0)
for index in range(len(list1)):
try:
print ("Venue: ", list1[index],  list2[index])
except Exception as e:
print(e)

相关内容

最新更新