Python 抓取网站链接到列表
Python scraping website links to a list
我正在尝试抓取 http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/ 网站 link,然后将 link 添加到空列表中。
这是我的代码:
from bs4 import BeautifulSoup
import requests
l = []
r = requests.get("http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/")
c=r.content
soup=BeautifulSoup(c,"html.parser")
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0])
现在我的结果是当我尝试打印网站的第一个 link 时:
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
.................
问题是,当我尝试打印网站的特定 link 时,link 打印了很多次,应该只打印一次。
行 print(l[0])
在 for
循环的每次迭代中运行,并始终打印列表的第一个元素。
for
循环结束后,您的列表将包含您要打印的所有链接。那时您可以遍历列表并打印每个元素。
更正代码的缩进。
print(l[0]) is inside the for loop that's why it is executed again and again.
from bs4 import BeautifulSoup
import requests
l = []
r = requests.get("http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/")
c=r.content
soup=BeautifulSoup(c,"html.parser")
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0]) #shift one tab backward
你犯了一个简单的逻辑错误。您的 print 语句当前在循环内。将它从循环范围中取出将解决您的问题。
固定版本:
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0])
循环执行后,l
数组将填充链接
我正在尝试抓取 http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/ 网站 link,然后将 link 添加到空列表中。
这是我的代码:
from bs4 import BeautifulSoup
import requests
l = []
r = requests.get("http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/")
c=r.content
soup=BeautifulSoup(c,"html.parser")
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0])
现在我的结果是当我尝试打印网站的第一个 link 时:
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
/soccer/england/premier-league-2016-2017/arsenal-everton/SGPa5fvr/
.................
问题是,当我尝试打印网站的特定 link 时,link 打印了很多次,应该只打印一次。
行 print(l[0])
在 for
循环的每次迭代中运行,并始终打印列表的第一个元素。
for
循环结束后,您的列表将包含您要打印的所有链接。那时您可以遍历列表并打印每个元素。
更正代码的缩进。
print(l[0]) is inside the for loop that's why it is executed again and again.
from bs4 import BeautifulSoup
import requests
l = []
r = requests.get("http://www.betexplorer.com/soccer/england/premier-league-2016-2017/results/")
c=r.content
soup=BeautifulSoup(c,"html.parser")
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0]) #shift one tab backward
你犯了一个简单的逻辑错误。您的 print 语句当前在循环内。将它从循环范围中取出将解决您的问题。
固定版本:
for link in soup.find_all("a",{"class":"in-match"}):
href=link.get('href')
l.append(href)
print(l[0])
循环执行后,l
数组将填充链接