2013-12-09 6 views
1

Я пытаюсь получить веб-ссылку на следующем, используя BeautifulSoupИзвлечение ссылки из URL с помощью 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' 

ответ

2

Используйте .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/' 
1

Вам нужно распаковать список, чтобы Попробуйте вместо этого:

nextlink = soup.findAll("div", {"class" : "alignright single"})[0] 

Или, так как есть только один Сопоставьте find метод также должен работать:

nextlink = soup.find("div", {"class" : "alignright single"}) 
Смежные вопросы