【发布时间】:2014-04-20 00:53:09
【问题描述】:
我编写了一个代码,它从指定的 url 中提取所有链接。我从在线视频教程中获得了这个想法。当我尝试使用 nytimes.com 时,如果成功了。但是当我尝试使用yell.com 时,我抛出了一个错误:“错误:HTTP 错误416:请求的范围不能满足-http://www.yell.com/”。我应该采用什么技术来绕过这个。
import urllib.parse;
import urllib;
from bs4 import BeautifulSoup;
##url = "http://nytimes.com";
url = "http://www.yell.com/";
urls = [url];
visited = [url];
while(len(urls) > 0):
try:
htmltext = urllib.request.urlopen(urls[0]).read();
soup = BeautifulSoup(htmltext);
urls.pop(0);
print(len(urls));
for tag in soup.findAll('a',href=True) :
tag['href'] = urllib.parse.urljoin(url,tag['href']);
if(url in tag['href'] and tag['href'] not in visited) :
urls.append(tag['href']);
visited.append(tag['href']);
except urllib.error.HTTPError as e:
print("Error: " + str(e)
+ " - " + url);
print(visited);
【问题讨论】:
-
提示:使用
set()换成visited,速度会快很多。而且我的印象是,yell.com 是由 javascript 加载的,因此可能是您的问题。 -
set() 访问?我无法理解。你能说得简短一点吗?使用“Selenium”是抓取 javascript 加载页面的好选择吗?
标签: python beautifulsoup web-crawler