如何使用Python检索网页的链接并复制链接的URL地址?
如何使用Python检索网页的链接并复制链接的URL地址?
这里是一个使用BeautifulSoup的SoupStrainer类的简短代码段:
import httplib2
from bs4 import BeautifulSoup, SoupStrainer
http = httplib2.Http()
status, response = http.request('http://www.nytimes.com')
for link in BeautifulSoup(response, parse_only=SoupStrainer('a')):
if link.has_attr('href'):
print(link['href'])
BeautifulSoup文档实际上相当好,并涵盖了许多典型场景:
https://www.crummy.com/software/BeautifulSoup/bs4/doc/
编辑:请注意,如果您事先知道要解析的内容,可以使用SoupStrainer类,因为它在内存和速度方面更加高效。
/usr/local/lib/python2.7/site-packages/bs4/__init__.py:128: UserWarning: BeautifulSoup构造函数中的"parseOnlyThese"参数已更名为"parse_only。"
- BenDundeehas_attr
。相反,我看到有一个叫做has_key
的东西,并且它可以使用。 - user2796118为了完整起见,以下是BeautifulSoup 4版本,使用服务器提供的编码:
from bs4 import BeautifulSoup
import urllib.request
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib.request.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().get_param('charset'))
for link in soup.find_all('a', href=True):
print(link['href'])
或 Python 2 版本:
from bs4 import BeautifulSoup
import urllib2
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = urllib2.urlopen("http://www.gpsbasecamp.com/national-parks")
soup = BeautifulSoup(resp, parser, from_encoding=resp.info().getparam('charset'))
for link in soup.find_all('a', href=True):
print link['href']
并且还有一个使用 requests
库的版本,如下所示即可在 Python 2 和 3 中运行:
from bs4 import BeautifulSoup
from bs4.dammit import EncodingDetector
import requests
parser = 'html.parser' # or 'lxml' (preferred) or 'html5lib', if installed
resp = requests.get("http://www.gpsbasecamp.com/national-parks")
http_encoding = resp.encoding if 'charset' in resp.headers.get('content-type', '').lower() else None
html_encoding = EncodingDetector.find_declared_encoding(resp.content, is_html=True)
encoding = html_encoding or http_encoding
soup = BeautifulSoup(resp.content, parser, from_encoding=encoding)
for link in soup.find_all('a', href=True):
print(link['href'])
soup.find_all('a', href=True)
调用会找到所有拥有 href
属性的 <a>
元素,没有此属性的元素会被跳过。
BeautifulSoup 3 在2012年3月停止开发;新项目应该始终使用 BeautifulSoup 4。
请注意,您应该将 HTML 从字节中解码交给 BeautifulSoup。您可以通知 BeautifulSoup 找到在 HTTP 响应标头中找到的字符集以帮助解码,但这个方法可能会错误并与在 HTML 中找到的 <meta>
标头信息冲突,因此上面的示例使用 BeautifulSoup 内部类方法 EncodingDetector.find_declared_encoding()
确保这样的嵌入式编码提示胜过配置错误的服务器。
对于 requests
,如果响应具有 text/*
MIME 类型,则 response.encoding
属性默认为 Latin-1,即使未返回字符集也是如此。这与 HTTP RFCs 一致,但在 HTML 解析中使用时很麻烦,所以当 Content-Type 标头中没有设置 charset
时,应忽略该属性。
虽然有人推荐BeautifulSoup,但最好使用lxml。尽管名字中有"XML",但它也可以用于解析和抓取HTML。它比BeautifulSoup快得多,并且甚至比BeautifulSoup(以其著名)更好地处理“损坏”的HTML。如果您不想学习lxml API,它还具有适用于BeautifulSoup的兼容API。
除非您在Google App Engine或某些不允许使用纯Python之外的领域,否则没有理由再使用BeautifulSoup了。
lxml.html还支持CSS3选择器,因此这种事情变得微不足道。
使用lxml和xpath的示例如下:
import urllib
import lxml.html
connection = urllib.urlopen('http://www.nytimes.com')
dom = lxml.html.fromstring(connection.read())
for link in dom.xpath('//a/@href'): # select the url in href for all a tags(links)
print link
lxml
,BeautifulSoup 4将使用它作为默认解析器。 - Martijn Pietersimport urllib2
import BeautifulSoup
request = urllib2.Request("http://www.gpsbasecamp.com/national-parks")
response = urllib2.urlopen(request)
soup = BeautifulSoup.BeautifulSoup(response)
for a in soup.findAll('a'):
if 'national-park' in a['href']:
print 'found a url with national-park in the link'
urllib2
和 BeautifulSoup4
来检索网页中所有可用链接的示例代码:import urllib2
from bs4 import BeautifulSoup
url = urllib2.urlopen("http://www.espncricinfo.com/").read()
soup = BeautifulSoup(url)
for line in soup.find_all('a'):
print(line.get('href'))
链接可以包含多种属性,因此您可以将这些属性的列表传递给select
。
例如,使用src
和href
属性(这里我使用以^运算符开头来指定这些属性值都是以http开头):
from bs4 import BeautifulSoup as bs
import requests
r = requests.get('https://stackoverflow.com/')
soup = bs(r.content, 'lxml')
links = [item['href'] if item.get('href') is not None else item['src'] for item in soup.select('[href^="http"], [src^="http"]') ]
print(links)
[attr^=value]
匹配具有属性名为 attr 且值以 value 开头的元素。
通常使用的操作符还包括 $
(以某些值结尾)和 *
(包含某些值)。有关完整语法列表,请参见上面的链接。
import requests
import lxml.html
dom = lxml.html.fromstring(requests.get('http://www.nytimes.com').content)
[x for x in dom.xpath('//a/@href') if '//' in x and 'nytimes.com' not in x]
这个脚本可以满足您的需求,而且还能将相对链接转换为绝对链接。
import urllib
import lxml.html
import urlparse
def get_dom(url):
connection = urllib.urlopen(url)
return lxml.html.fromstring(connection.read())
def get_links(url):
return resolve_links((link for link in get_dom(url).xpath('//a/@href')))
def guess_root(links):
for link in links:
if link.startswith('http'):
parsed_link = urlparse.urlparse(link)
scheme = parsed_link.scheme + '://'
netloc = parsed_link.netloc
return scheme + netloc
def resolve_links(links):
root = guess_root(links)
for link in links:
if not link.startswith('http'):
link = urlparse.urljoin(root, link)
yield link
for link in get_links('http://www.google.com'):
print link
为了找到所有的链接,在这个例子中我们将使用urllib2模块和re模块。 *在re模块中最强大的函数之一是"re.findall()"。虽然re.search()用于查找模式的第一个匹配项,但re.findall()查找所有匹配项并将它们作为字符串列表返回,每个字符串代表一个匹配项*
import urllib2
import re
#connect to a URL
website = urllib2.urlopen(url)
#read html code
html = website.read()
#use re.findall to get all the links
links = re.findall('"((http|ftp)s?://.*?)"', html)
print links
仅获取链接,无需使用 B.soup 和正则表达式:
import urllib2
url="http://www.somewhere.com"
page=urllib2.urlopen(url)
data=page.read().split("</a>")
tag="<a href=\""
endtag="\">"
for item in data:
if "<a href" in item:
try:
ind = item.index(tag)
item=item[ind+len(tag):]
end=item.index(endtag)
except: pass
else:
print item[:end]
对于更复杂的操作,当然还是首选BSoup。
<a
和href
之间有一些其他内容呢?比如rel="nofollow"
或onclick="..."
甚至只是一个换行符?https://dev59.com/X3I-5IYBdhLWcg3wq6do#1732454 - dimo414
/info-service/downloads/#unserekataloge'
。无法获取完整的可访问链接吗?而不仅仅是子链接的一部分?我想获取网站上所有可用pdf的链接。@MujeebIshaque - x89