Skip to main content
 首页 » 编程设计

python之使用 BeautifulSoup 循环访问 URL 列表以进行网络抓取

2024年10月24日11落叶无声

我想从具有以下形式 URL 的网站中提取一些信息: http://www.pedigreequery.com/american+pharoah 其中“american+pharoah”是许多马名之一的扩展名。 我有一个要搜索的马名列表,我只需要弄清楚如何在“http://www.pedigreequery.com/”之后插入这些名称

这是我目前拥有的:

import csv 
allhorses = csv.reader(open('HORSES.csv') ) 
rows=list(allhorses) 
 
import requests  
from bs4 import BeautifulSoup 
for i in rows:      # Number of pages plus one  
    url = "http://www.pedigreequery.com/".format(i) 
    r = requests.get(url) 
    soup = BeautifulSoup(r.content) 
    letters = soup.find_all("a", class_="horseName") 
    print(letters) 

当我打印出 url 时,末尾没有马名,只有引号中的 URL。末尾的字母/打印声明只是为了检查它是否真的访问了该网站。 这就是我所看到的用于循环 URL 的方式,这些 URL 在最后按数字更改 - 我还没有找到有关按字符更改的 URL 的建议。

谢谢!

请您参考如下方法:

您的格式中缺少占位符,因此请将格式扫描至:

url = "http://www.pedigreequery.com/{}".format(i) 
                                     ^ 
                                   #add placeholder 

此外,您最多只能从 rows=list(allhorses) 获取列表列表,因此您将传递一个列表而不是字符串/马名,如果您有一匹马,只需正常打开文件每行并迭代文件对象剥离换行符。

假设每行一个马名,整个工作代码将是:

import requests 
from bs4 import BeautifulSoup 
 
with open("HORSES.csv") as f: 
    for horse in map(str.strip,f):      # Number of pages plus one 
        url = "http://www.pedigreequery.com/{}".format(horse) 
        r = requests.get(url) 
        soup = BeautifulSoup(r.content) 
        letters = soup.find_all("a", class_="horseName") 
        print(letters) 

如果每行有多匹马,您可以使用 csv 库,但您需要一个内部循环:

with open("HORSES.csv") as f: 
    for row in csv.reader(f):    
        # Number of pages plus one 
        for horse in row: 
            url = "http://www.pedigreequery.com/{}".format(horse) 
            r = requests.get(url) 
            soup = BeautifulSoup(r.content) 
            letters = soup.find_all("a", class_="horseName") 
            print(letters) 

最后,如果您没有正确存储名称,您有几个选项,其中最简单的是拆分和创建手动创建查询。

  url = "http://www.pedigreequery.com/{}".format("+".join(horse.split()))