【发布时间】:2016-05-23 05:05:47
【问题描述】:
我正在尝试提取这样写的链接:
<h2 class="section-heading">
<a href="http://www.nytimes.com/pages/arts/index.html">Arts »</a>
</h2>
我的代码是:
from bs4 import BeautifulSoup
import requests, re
def get_data():
url='http://www.nytimes.com/'
s_code=requests.get(url)
plain_text = s_code.text
soup = BeautifulSoup(plain_text)
head_links=soup.findAll('h2', {'class':'section-heading'})
for n in head_links :
a = n.find('a')
print a
print n.get['href']
#print a['href']
#print n.get('href')
#headings=n.text
#links = n.get('href')
#print headings, links
get_data()
类似的“print a”只是在<h2 class=section-heading>内打印出整个<a>行,即
<a href="http://www.nytimes.com/pages/world/index.html">World »</a>
但是当我执行“print n.get['href']”时,它会抛出一个错误;
print n.get['href']
TypeError: 'instancemethod' object has no attribute '__getitem__'
我在这里做错了吗?请帮忙
我在这里找不到一些类似的案例问题,我的问题在这里有点独特,我正在尝试提取特定类名部分标题内的链接。
【问题讨论】:
-
另外,我认为你的意思是
a.get('href')而不是n.get -
@cricket_007 重复的问题并没有回答这个确切的错误,尽管它很有用;它也适用于早期版本的库。
-
@AnttiHaapala - 我正在解决问题的最终目标,而不是错误,但是是的,我明白你在说什么
标签: python beautifulsoup python-requests bs4