【问题标题】:How to join 2 Webscraped lists together as one如何将 2 个 Webscraped 列表合并为一个
【发布时间】:2018-10-30 15:27:18
【问题描述】:

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

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 Street\r\nNew York City, 94710\n\n212.613.5536\n'
'\n \nEllis Island\r\nNew York, NY 10004\n\n212.613.5535\n'
'\n \n242 W 41st St\r\nNew York, NY 10036\n\n212.613.5535\n'
'\n \n135 W 18th St\r\nNew York, NY 10011\n\n212.613.5535\n'
'\n \n1871 Broadway\r\nNew York, NY 10023\n\n212.613.5536\n'

尝试加入两者:

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

输出:

Venue: NYIT Auditorium on Broadway

1871 Broadway
New York, NY 10023

212.613.5536

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

【问题讨论】:

  • 请考虑显示更多代码,以便我们查看逻辑并了解为什么它只显示一个实例。
  • @JerryHu 那里 :)
  • 还有显示功能?
  • @JerryHu 一切都在那里。

标签: python html python-3.x web-scraping jupyter


【解决方案1】:

在不确切知道 display() 做什么的情况下,我的猜测是您没有打印所有“实例”,因为您只能从两个 for 循环的最后一次迭代中获得结果。

在不改变结构的情况下,最快的方法是将两个 bs4 scraps 的输出保存到两个列表中,并使用循环显示它们的内容。

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)

【讨论】:

  • 非常感谢@JerryHu!这行得通!我真的很感谢它,伙计,你为我节省了很多时间。
猜你喜欢
  • 1970-01-01
  • 2014-08-04
  • 1970-01-01
  • 2021-06-02
  • 1970-01-01
  • 2018-04-26
  • 1970-01-01
  • 2020-07-19
  • 1970-01-01
相关资源
最近更新 更多