【问题标题】:Scraping: issues receiving table data when looping with request抓取:使用请求循环时接收表数据的问题
【发布时间】:2018-11-18 00:57:02
【问题描述】:

更新: 该代码只能暂时起作用。有 2000 多个加密货币,此时我有 492 个独特的文件及其历史记录。

当我尝试运行一个被自己跳过的 url 时,它可以工作。因此,我认为它已经缩小到与内容的要求有关。

在继续代码之前,是否可以确保我感兴趣的表已完全加载?

更新: 我让它正常工作。我认为您可以在我试图从中抓取的网站上每秒或分钟执行的请求是有限的。 我在每个请求之间延迟了 3 秒,现在它可以工作了!!!! 感谢你们俩的帮助。尽管它没有提供直接的答案,但它让我走上了正确的道路来弄清楚它。

from bs4 import BeautifulSoup
import requests
import pandas as pd
import time

def scraping(url):
    global line
    content = requests.get(url).content
    soup = BeautifulSoup(content,'html.parser')
    table = soup.find('table', {'class': 'table'})
    if not table:
        print(url)
        return
    data = [[td.text.strip() for td in tr.findChildren('td')] for tr in table.findChildren('tr')]
    df = pd.DataFrame(data)
    df.drop(df.index[0], inplace=True) 
    df[0] =  pd.to_datetime(df[0])
    for i in range(1,7):
        df[i] = pd.to_numeric(df[i].str.replace(",","").str.replace("-",""))
    df.columns = ['Date','Open','High','Low','Close','Volume','Market Cap']
    df.set_index('Date',inplace=True)
    df.sort_index(inplace=True)
    return df.to_csv(line + '_historical_data.csv')


with open("list_of_urls.txt") as file:
    for line in file:
        time.sleep(3)
        line = line.strip()
        start = "https://coinmarketcap.com/currencies/"
        end = "/historical-data/?start=20000101&end=21000101"
        url = start + line + end
        scraping(url)

【问题讨论】:

    标签: python-3.x pandas beautifulsoup


    【解决方案1】:

    可能是 URL 未找到 404 或页面没有表格。调试规范化循环并打印当前处理的加密名称

    table = soup.find('table', {'class': 'table'})
    if not table:
        print('no table')
        return
    

    【讨论】:

    【解决方案2】:

    你可以只执行findChildren(),返回的tabletr对象不是NoneType,如下:

    data = [[td.text.strip() for td in tr.findChildren('td') if td] for tr in table.findChildren('tr') if tr] if table else []
    if len(data) > 0:
        # process your data here
    

    希望对你有帮助。

    【讨论】:

    • 很遗憾没有。刚试了一下。同样的错误。在我收到错误之前,我通过了前 38 个。我觉得这很奇怪。
    • 现在怎么样(见我更新的答案)?通过添加if tableif td。应该很有希望。
    • 嗨,现在它给了我这个:“IndexError: index 0 is out of bounds for axis 0 with size 0” for this line "df.drop(df.index[0], inplace=真)”
    • 因为如果没有 td 单元格,您将需要跳过处理。看看我更新的答案。希望它现在有效。
    猜你喜欢
    • 1970-01-01
    • 2021-10-28
    • 1970-01-01
    • 2018-09-23
    • 1970-01-01
    • 1970-01-01
    • 2019-10-21
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多