【问题标题】:How can Beautifulsoup scrape the pages inside this list of hyperlinks?Beautifulsoup 如何抓取此超链接列表中的页面?
【发布时间】:2022-01-21 02:22:24
【问题描述】:

我正在尝试抓取此页面左侧超链接的内容。我已经能够抓取超链接的内容,所以现在我尝试在页面左侧的每个单独的超链接上运行脚本。

网址:https://bitinfocharts.com/top-100-richest-dogecoin-addresses-3.html

我认为需要做的是 url 是一个动态变量,并且该变量是一个循环,它将遍历上面 URL 中的所有超链接。虽然我不确定这是否是最好的方法,因为这是我的第一个项目

非常感谢任何建议。

这是我尝试插入的代码。

import csv
import requests
from bs4 import BeautifulSoup as bs

url = 'https://bitinfocharts.com/dogecoin/address/DN5Hp2kCkvCsdwr5SPmwHpiJgjKnC5wcT7'
headers = {"User-Agent": "Mozilla/5.0"}

r = requests.get(url, headers=headers)

soup = bs(r.content, 'lxml')
table = soup.find(id="table_maina")
headers = []
datarows = []


#Get crypto address for the filename
item = soup.find('h1').text
newitem = item.replace('Dogecoin','')
finalitem = newitem.replace('Address','')



for row in table.find_all('tr'):
    heads = row.find_all('th')
    if heads:
        headers = [th.text for th in heads]
    else:
        datarows.append([td.text for td in row.find_all('td')])

fcsv = csv.writer(open(f'{finalitem}.csv', 'w', newline=''))
fcsv.writerow(headers)
fcsv.writerows(datarows)

【问题讨论】:

  • 每个链接都放在自己的 csv 中吗?
  • 是的,每个链接都将进入它自己的 CSV 文件中,该 CSV 文件以各自的加密地址命名。

标签: python web-scraping beautifulsoup


【解决方案1】:

一种简单的方法是发出初始请求并提取表格第二列中的所有链接。

然后循环这些链接,发出请求,并继续使用现有代码,但还要处理没有表的情况。

import csv
import requests
from bs4 import BeautifulSoup as bs

headers = []
datarows = []

with requests.Session() as s:
    s.headers = {"User-Agent": "Safari/537.36"}
    r = s.get('https://bitinfocharts.com/top-100-richest-dogecoin-addresses-3.html')
    soup = bs(r.content, 'lxml')
    address_links = [i['href'] for i in soup.select('.table td:nth-child(2) > a')]
    
    for url in address_links:

        r = s.get(url)
        soup = bs(r.content, 'lxml')
        table = soup.find(id="table_maina")
        
        if table:
            item = soup.find('h1').text
            newitem = item.replace('Dogecoin','')
            finalitem = newitem.replace('Address','')

            for row in table.find_all('tr'):
                heads = row.find_all('th')
                if heads:
                    headers = [th.text for th in heads]
                else:
                    datarows.append([td.text for td in row.find_all('td')])

            fcsv = csv.writer(open(f'{finalitem}.csv', 'w', newline=''))
            fcsv.writerow(headers)
            fcsv.writerows(datarows)
        else:
            print('no table for: ', url)

【讨论】:

    猜你喜欢
    • 2020-01-23
    • 1970-01-01
    • 1970-01-01
    • 2021-05-31
    • 2016-04-01
    • 2019-10-27
    • 2014-12-07
    • 2019-08-14
    • 1970-01-01
    相关资源
    最近更新 更多