python - 使用 Beautifulsoup 从 url 中提取链接

标签 python beautifulsoup

我正在尝试使用 beautifulsoup 获取以下网页链接

<div class="alignright single">
<a href="http://www.dailyhadithonline.com/2013/07/21/hadith-on-clothing-women-should-lower-their-garments-to-cover-their-feet/" rel="next">Hadith on Clothing: Women should lower their garments to cover their feet</a> &raquo;    </div>
</div>

我的代码如下

from bs4 import BeautifulSoup                                                                                                                                 
import urllib2                                                                                                
url1 = "http://www.dailyhadithonline.com/2013/07/21/hadith-on-clothing-the-lower-garment-should-be-hallway-between-the-shins/"

content1 = urllib2.urlopen(url1).read()
soup = BeautifulSoup(content1) 

nextlink = soup.findAll("div", {"class" : "alignright single"})
a = nextlink.find('a')
print a.get('href')

出现如下错误,求助

a = nextlink.find('a')
AttributeError: 'ResultSet' object has no attribute 'find'

最佳答案

使用 .find()如果你只想找到一个匹配项:

nextlink = soup.find("div", {"class" : "alignright single"})

循环所有匹配项:

for nextlink in soup.findAll("div", {"class" : "alignright single"}):
    a = nextlink.find('a')
    print a.get('href')

后半部分也可以表示为:

a = nextlink.find('a', href=True)
print a['href']

哪里href=True部分仅匹配具有 href 的元素属性,这意味着您不必使用 a.get()因为属性在那里(或者,没有找到 <a href="..."> 链接并且 a 将是 None)。

对于您问题中给定的 URL,只有一个这样的链接,因此 .find()可能是最方便的。甚至可以只使用:

nextlink = soup.find('a', rel='next', href=True)
if nextlink is not None:
    print a['href']

不需要找周边div . rel="next"属性看起来足以满足您的特定需求。

作为一个额外的提示:使用响应头来告诉 BeautifulSoup 页面使用什么编码; urllib2响应对象可以告诉您服务器认为 HTML 页面编码的字符集(如果有的话):

response = urllib2.urlopen(url1)
soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))

所有部分的快速演示:

>>> import urllib2
>>> from bs4 import BeautifulSoup
>>> response = urllib2.urlopen('http://www.dailyhadithonline.com/2013/07/21/hadith-on-clothing-the-lower-garment-should-be-hallway-between-the-shins/')
>>> soup = BeautifulSoup(response.read(), from_encoding=response.info().getparam('charset'))
>>> soup.find('a', rel='next', href=True)['href']
u'http://www.dailyhadithonline.com/2013/07/21/hadith-on-clothing-women-should-lower-their-garments-to-cover-their-feet/'

关于python - 使用 Beautifulsoup 从 url 中提取链接,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20469596/

相关文章:

python - 从网站中提取特定行

python - 查找另一个标签之前的标签 BeautifulSoup

python - 每 3 个数字将列表中的数字相加

python - 如何根据 flask 中的先前值检索第二个值

Python 元类冲突/类型错误

Python BeautifulSoup - 无法读取网站分页

python - 使用 BeautifulSoup 和 Python 获取元标记内容属性

python - 网络抓取更新值

python - Google App Engine 配置 Endpoints API

使用 cpu 查找前 5 个进程的 Python 代码