我想从网址中提取一些信息,其网址格式为: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 = "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 lib,但是需要一个内部循环:
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()))
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句