优化Python刮刀
这是一个冗长的问题,我可能只需要有人给我指出正确的方向。我正在建立一个网络刮板,从ESPN的网站上抓取篮球运动员的信息。URL结构非常简单,因为每个玩家卡的URL中都有一个特定的id。为了获取信息,我正在写一个从1到6000的循环,从他们的数据库中抓取玩家。我的问题是,是否有一种更有效的方法来做到这一点优化Python刮刀,python,web-scraping,beautifulsoup,Python,Web Scraping,Beautifulsoup,这是一个冗长的问题,我可能只需要有人给我指出正确的方向。我正在建立一个网络刮板,从ESPN的网站上抓取篮球运动员的信息。URL结构非常简单,因为每个玩家卡的URL中都有一个特定的id。为了获取信息,我正在写一个从1到6000的循环,从他们的数据库中抓取玩家。我的问题是,是否有一种更有效的方法来做到这一点 from bs4 import BeautifulSoup from urllib2 import urlopen import requests import nltk import re
from bs4 import BeautifulSoup
from urllib2 import urlopen
import requests
import nltk
import re
age = [] # Empty List to store player ages
BASE = 'http://espn.go.com/nba/player/stats/_/id/' # Base Structure of Player Card URL
def get_age(BASE): #Creates a function
#z = range(1,6000) # Create Range from 1 to 6000
for i in range(1, 6000): # This is a for loop
BASE_U = BASE + str(i) + '/' # Create URL For Player
r = requests.get(BASE_U)
soup = BeautifulSoup(r.text)
#Prior to this step, I had to print out the soup object and look through the HTML in order to find the tag that contained my desired information
# Get Age of Players
age_tables = soup.find_all('ul', class_="player-metadata") # Grabs all text in the metadata tag
p = str(age_tables) # Turns text into a string
#At this point I had to look at all the text in the p object and determine a way to capture the age info
if "Age: " not in p: # PLayer ID doesn't exist so go to next to avoid error
continue
else:
start = p.index("Age: ") + len("Age: ") # Gets the location of the players age
end = p[start:].index(")") + start
player_id.append(i) #Adds player_id to player_id list
age.append(p[start:end]) # Adds player's age to age list
get_age(BASE)
任何帮助,即使是很小的,都将不胜感激。即使这只是给我指明了正确的方向,也不一定是一个直接的解决方案
谢谢,
Ben它就像网络安全中的端口扫描器,多线程将大大加快您的编程速度。不仅效率更高,而且更具组织性和可扩展性的方法将涉及切换到web抓取框架 您所遇到的主要性能问题是由于当前方法的“阻塞”性质-
Scrapy
将立即解决它,因为它基于twisted
,并且是完全异步的。我可能会从以下正则表达式开始,并使用以下正则表达式获取团队名册URL
\href="(/nba/teams/roster\?team=[^"]+)">([^<]+)</a>\
\href="(http://espn.go.com/nba/player/_/id/[^"]+)">([^<]+)</a>\
\href=“(/nba/teams/花名册\?team=[^”]+)”>([^Ah我听说过多线程。你知道容易上手的在线教程吗?我个人认为多处理
库的文档是一个很好的起点。如果文档对你来说不够好,你可以查阅该库的指南。谢谢!我会看看scrapy!@Ben sure,如果需要,请告诉我你需要帮助制作一个scrapy spider。你会惊讶地发现开始使用scrapy是多么容易。谢谢alecxe!我可能会联系你