【问题标题】:Beautiful soup looping through array of URLs美丽的汤循环通过 URL 数组
【发布时间】:2016-12-01 05:44:51
【问题描述】:

我正在尝试遍历一系列 URL 并从公司列表中抓取董事会成员。下面的循环似乎有问题,它只运行数组中的第一个元素并复制结果。对此的任何帮助将不胜感激。代码:

from bs4 import BeautifulSoup
import requests

#array of URLs to loop through, will be larger once I get the loop working correctly
tickers = ['http://www.reuters.com/finance/stocks/companyOfficers?symbol=AAPL.O', 'http://www.reuters.com/finance/stocks/companyOfficers?symbol=GOOG.O']

board_members = []
output = []
soup = BeautifulSoup(html, "html.parser")

for t in tickers:
    html = requests.get(t).text
    officer_table = soup.find('table', {"class" : "dataTable"})
    for row in officer_table.find_all('tr'):
        cols = row.find_all('td')
        if len(cols) == 4:
            board_members.append((t, cols[0].text.strip(), cols[1].text.strip(), cols[2].text.strip(), cols[3].text.strip()))

        for t, name, age, year_joined, position in board_members:
            output.append(('{} {:35} {} {} {}'.format(t, name, age, year_joined, position)))

【问题讨论】:

  • 此代码不应运行。 BeautifulSoup(html 会报错html 没有定义
  • 无论如何,考虑只存储列表中的符号。稍后在您发出请求时格式化 URL

标签: python web-scraping beautifulsoup


【解决方案1】:
soup = BeautifulSoup(html, "html.parser")

for t in tickers:
    html = requests.get(t).text
    officer_table = soup.find('table', {"class" : "dataTable"})

你把soup放到for循环之外,这会导致错误,因为当你使用BeautifulSoup(html, "html.parser")时'html'不存在 分配好html后放入循环中即可。

for t in tickers:
    html = requests.get(t).text
    soup = BeautifulSoup(html, "html.parser")
    officer_table = soup.find('table', {"class" : "dataTable"})

【讨论】:

    猜你喜欢
    • 2016-04-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多