【发布时间】:2017-09-04 14:27:13
【问题描述】:
为了练习,我一直在学习 Python 和使用 BeautifulSoup 进行网络抓取。我正在寻找一个可以在网站上找到团队页面并抓取团队成员姓名的程序。以下是“团队”页面的示例:http://plasticbank.org/team-speakers/
我发现所有团队页面的“团队”都明显更大,但并非所有网站都使用标题,因此很难通过它们进行解析。我已经用 urllib2 加载了一个 URL。我将如何浏览网站的主页并找到“团队”或任何具有特定主题的页面?和找联系方式是同一种问题,怎么让爬虫找到呢?
这是我的代码的完整部分:(这只是加载网站)
#Pre: url is a string containing the address of a website
#return: A string with the URL formatted to include http://
def ensureurl(url):
if '//' not in url:
return "http://" + url
else:
return url
#Pre: url is a string containing the address of a website
#return: The HTML code at that URL or an empty string if the URL could not be processed
def read_url(url):
url = ensureurl(url)
print url
try:
#User agent spoofing to trick sites into thinking the bot is a human.
#This does not work on all sites.
hdr = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:47.0) Gecko/20100101 Firefox/47.0',
'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
'Accept-Charset': 'ISO-8859-1,utf-8;q=0.7,*;q=0.3',
'Accept-Encoding': 'none',
'Accept-Language': 'en-US,en;q=0.8',
'Connection': 'keep-alive'}
request = urllib2.Request(url, headers=hdr)
return urllib2.urlopen(request).read()
except urllib2.HTTPError, e:
print e.fp.read()
return ""
【问题讨论】:
-
你写过什么代码吗?
-
我刚刚编辑了帖子以包含我的代码的完整部分
标签: python web-scraping beautifulsoup