【问题标题】:How to pull the same nested data from a list of URLs using BeautifulSoup如何使用 BeautifulSoup 从 URL 列表中提取相同的嵌套数据
【发布时间】:2019-07-13 11:35:03
【问题描述】:

下午好,

我对抓取比较陌生,我目前正忙于这个项目。要提取的预期数据是公司名称、地址、电话号码和公司 url(全部从嵌套网页中提取)。

主页 = http://www.therentalshow.com/find-exhibitors/sb-search/equipment/sb-inst/8678/sb-logid/242109-dcja1tszmylg308y/sb-page/1 嵌套页面 = http://www.therentalshow.com/exhibitor-detail/cid/45794/exhib/2019

我能够编译这个 url 列表,但我最难的是抓取每个单独的公司信息并以表格格式输出到 CSV。

from urllib.request import urlopen as uReq
from bs4 import BeautifulSoup as soup
import requests
import pandas as pd
import csv, os

my_url = 'http://www.therentalshow.com/find-exhibitors/sb-search/equipment/sb-inst/8678/sb-logid/242109-dcja1tszmylg308y/sb-page/1'
uClient = uReq(my_url)
page_html = uClient.read()
uClient.close()
page_soup = soup(page_html, 'lxml')

#create list of urls from main page
urls = []
tags = page_soup.find_all('a',{'class':'avtsb_title'})
for tag in tags:
    urls.append('http://www.therentalshow.com' + tag.get('href'))

#iterate through each page to return company data
for url in urls:
    site = uReq(url)
    soups = soup(site, 'lxml')

    name = page_soup.select('h2')
    address = page_soup.find('span',{'id':'dnn_ctr8700_TRSExhibitorDetail_lblAddress'})
    city = page_soup.find('span',{'id':'dnn_ctr8700_TRSExhibitorDetail_lblCityStateZip'})
    phone = page_soup.find('span',{'id':'dnn_ctr8700_TRSExhibitorDetail_lblPhone'})
    website = page_soup.find('a',{'id':'dnn_ctr8700_TRSExhibitorDetail_hlURL'})

    os.getcwd()
    outputFile = open('output2.csv', 'a', newline='')
    outputWriter = csv.writer(outputFile)
    outputWriter.writerow([name, address, city, phone, website])

我返回的输出是

[],,,,
[],,,,

总共 99 行。我的总链接列表是 100。

我希望上述变量的名称作为我的 csv 文件的标题,但我当前的输出不是我想要的。我很迷茫,所以任何帮助都会非常感激。谢谢!

【问题讨论】:

    标签: python pandas web-scraping beautifulsoup screen-scraping


    【解决方案1】:

    我目前无法完全测试,因为requests 挂起,但您需要提取返回元素的.text。此外,您的第一个选择是一个列表,因此例如更改为 select_one 或适当地索引到列表中。我更喜欢 css 选择器而不是 find。

    我从一页提取html到html变量中

    page_soup = bs(html, 'lxml')
    name = page_soup.select_one('h2').text
    address = page_soup.select_one('#dnn_ctr8700_TRSExhibitorDetail_lblAddress').text
    city = page_soup.select_one('#dnn_ctr8700_TRSExhibitorDetail_lblCityStateZip').text
    phone = page_soup.select_one('#dnn_ctr8700_TRSExhibitorDetail_lblPhone').text
    website = page_soup.select_one('#dnn_ctr8700_TRSExhibitorDetail_hlURL').text
    print([name, address, city, phone, website])
    

    使用上述更改从前两个链接复制 html 会产生:

    ['A-1 Scaffold Manufacturing', '590 Commerce Pkwy', 'Hays, KS', '785-621-5121', 'www.a1scaffoldmfg.com']
    ['Accella Tire Fill Systems', '2003 Curtain Pole Rd', 'Chattanooga, TN', '423-697-0400', 'www.accellatirefill.com']
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2021-10-11
      • 2018-02-18
      • 1970-01-01
      • 2014-08-18
      • 2017-12-31
      • 1970-01-01
      • 2017-11-11
      相关资源
      最近更新 更多