我正在使用一个简单的python代码来尝试获取一个URL并清除该URL中每个网页(所有html子页面,如果在主页/根页面下)中提到的所有其他URL。这是我的代码:
import urllib
import urllib2
import re
import socks
import socket
socks.setdefaultproxy(socks.PROXY_TYPE_SOCKS5, "127.0.0.1", 9050)
socket.socket = socks.socksocket
req = urllib2.Request('http://www.python.org')
#connect to a URL
try:
website = urllib2.urlopen(req)
except urllib2.URLError as e:
print "Error Reason:" ,e.reason
else:
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
现在我收到一个简单的错误,其中模块socks无法识别。我想我必须复制" socks.py"在Python的lib / site-packages目录下的正确路径中。
我已将socks模块添加到我的代码中,因为我的python脚本无法连接到网址http://www.python.org
。我的问题是我正确使用socks
吗?
我的脚本也会处理根网址下的所有网页吗?因为我想从根URL下的所有这些网页中删除所有urls
。
另外,如何查看我的代码port
行中要提及的setdefaultproxy
内容?
答案 0 :(得分:1)
我建议您使用BeautifulSoup进行Webscraping目的。下面是它的代码,有更简单的方法。
import requests
from bs4 import BeautifulSoup
r=requests.get("http://www.python.org")
c=r.content
soup=BeautifulSoup(c,"html.parser")
anchor_list=[a['href'] for a in soup.find_all('a', href=True) if a.text.strip()]
print(anchor_list)
希望它有所帮助!