如何使我的python代码请求URL并根据需要从网页获取信息

问题描述 投票:0回答:1

我正在使用一个简单的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无法识别。我想我必须在Python的lib / site-packages目录下的正确路径中复制“socks.py”。

我已经将socks模块添加到我的代码中,因为我的python脚本无法连接到url http://www.python.org。我的问题是我正确使用socks吗?

我的脚本也会处理根URL下的所有网页吗?因为我想从根URL下的所有这些网页中删除所有urls

另外,我如何检查port在我的代码的setdefaultproxy行中提到的是什么?

python html socks
1个回答
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)

希望能帮助到你 !

© www.soinside.com 2019 - 2024. All rights reserved.