【问题标题】:Python requests and beautifulsoup4, collecting only the "href" linksPython requests 和 beautifulsoup4,只收集“href”链接
【发布时间】:2016-12-19 04:10:05
【问题描述】:
from bs4 import BeautifulSoup
import requests

url = "https://www.brightscope.com/ratings"
headers = {'User-Agent':'Mozilla/5.0'}
page = requests.get(url)
soup = BeautifulSoup(page.text, "html.parser")

data = soup.find_all('li',{"class":"more-data"})+soup.findAll('li', {"class":"more-data topten"})
for item in data:
   print(item('a'))

我想只打印 href,但我似乎无法弄清楚这一点。我看过不同的视频,但无法理解。我究竟做错了什么?我知道上面的代码正在打印“a”标签的内容,但我只需要href。

【问题讨论】:

    标签: python beautifulsoup html-parsing python-requests


    【解决方案1】:

    您需要的是使用类似字典的方式访问元素的属性

    [a['href'] for a in item('a')]
    

    另外,您可以改进定位 li 元素的方式,而不是:

    data = soup.find_all('li',{"class":"more-data"})+soup.findAll('li', {"class":"more-data topten"})
    for item in data:
       print(item('a'))
    

    你可以这样做:

    links = soup.select("li.more-data a")
    for a in links:
        print(a["href"])
    

    其中li.more-data aCSS selector,它将匹配li 元素中的所有a 元素与more-data 类。

    【讨论】:

      猜你喜欢
      • 2020-09-04
      • 2018-06-09
      • 1970-01-01
      • 1970-01-01
      • 2014-08-07
      • 1970-01-01
      • 1970-01-01
      • 2019-04-04
      • 2020-03-01
      相关资源
      最近更新 更多