用urllib2避免503错误
我刚开始学习用Python进行网页抓取,所以不太确定自己做得对不对。
我在用一个脚本,这个脚本调用了BeautifulSoup来解析谷歌搜索前10页的链接。我用stackoverflow.com测试了一下,结果一切正常。后来我又试了其他网站,想看看这个脚本在处理更多谷歌页面请求时是否也能正常工作,但结果出现了503错误。然后我换了一个网址测试,刚开始能用几次,结果又出现了503错误。现在我传给它的每个网址都出现503错误。有没有什么建议?
import sys # Used to add the BeautifulSoup folder the import path
import urllib2 # Used to read the html document
if __name__ == "__main__":
### Import Beautiful Soup
### Here, I have the BeautifulSoup folder in the level of this Python script
### So I need to tell Python where to look.
sys.path.append("./BeautifulSoup")
from BeautifulSoup import BeautifulSoup
### Create opener with Google-friendly user agent
opener = urllib2.build_opener()
opener.addheaders = [('User-agent', 'Mozilla/5.0')]
### Open page & generate soup
### the "start" variable will be used to iterate through 10 pages.
for start in range(0,10):
url = "http://www.google.com/search?q=site:stackoverflow.com&start=" + str(start*10)
page = opener.open(url)
soup = BeautifulSoup(page)
### Parse and find
### Looks like google contains URLs in <cite> tags.
### So for each cite tag on each page (10), print its contents (url)
for cite in soup.findAll('cite'):
print cite.text
2 个回答
0
正如Ettore所说,抓取搜索结果是违反我们的服务条款的。不过,你可以看看WebSearch的API,特别是文档的底部部分,那里面应该会给你一些关于如何在非JavaScript环境中访问这个API的提示。
5
根据谷歌的服务条款,不允许自动化查询。
想了解更多信息,可以查看这篇文章:来自你电脑的异常流量,还有谷歌的服务条款。