使用 BeautifulSoup 提取链接的标题

Man*_*edi 9 python beautifulsoup web-scraping python-2.7 python-requests

我正在尝试使用 BeautifulSoup 提取链接的标题。我正在使用的代码如下:

url = "http://www.example.com"
source_code = requests.get(url)
plain_text = source_code.text
soup = BeautifulSoup(plain_text, "lxml")
for link in soup.findAll('a', {'class': 'a-link-normal s-access-detail-page  a-text-normal'}):
    title = link.get('title')
    print title
Run Code Online (Sandbox Code Playgroud)

现在,一个示例link元素包含以下内容:

<a class="a-link-normal s-access-detail-page a-text-normal" href="http://www.amazon.in/Introduction-Computation-Programming-Using-Python/dp/8120348664" title="Introduction To Computation And Programming Using Python"><h2 class="a-size-medium a-color-null s-inline s-access-title a-text-normal">Introduction To Computation And Programming Using <strong>Python</strong></h2></a>
Run Code Online (Sandbox Code Playgroud)

但是,运行上述代码后,没有任何显示。如何提取存储在title锚标记的属性中的值link

Vik*_*jha 8

好吧,您似乎在s-access-detail-page和之间放置了两个空格a-text-normal,这反过来又找不到任何匹配的链接。尝试使用正确数量的空格,然后打印找到的链接数量。此外,您可以打印标签本身 -print link

import requests
from bs4 import BeautifulSoup

url = "http://www.amazon.in/s/ref=nb_sb_noss_1?url=search-alias%3Daps&field-keywords=python"
source_code = requests.get(url)
plain_text = source_code.content
soup = BeautifulSoup(plain_text, "lxml")
links = soup.findAll('a', {'class': 'a-link-normal s-access-detail-page a-text-normal'})
print len(links)
for link in links:
    title = link.get('title')
    print title
Run Code Online (Sandbox Code Playgroud)