【问题标题】:Beautiful soup getting name of <a> element within a divBeautifulsoup 在 div 中获取 <an> 元素的名称
【发布时间】:2015-03-04 18:36:37
【问题描述】:

我是第一次使用 Beautiful Soup,我正在尝试获取网页中特定元素的值。

例如在这段代码中sn-p:

<div class="otg-vendor-name"><a class="otg-vendor-name-link"     href="http://www.3brotherskitchen.com" target="_blank">3 Brothers Kitchen</a></div>

我希望从 .

到目前为止,我尝试了一些似乎不起作用的方法:

import urllib2
from bs4 import BeautifulSoup

url    = "http://someurl"
def get_all_vendors():
   try:
      web_page = urllib2.urlopen(url).read()
      soup = BeautifulSoup(web_page)
      c = []
      c.append(soup.findAll("div", {"class":'otg-vendor-name'}).contents)
    print c

   except urllib2.HTTPError:
   print("HTTPERROR!")

   except urllib2.URLError:
   print("URLERROR!")

   return c

【问题讨论】:

    标签: beautifulsoup html-parsing


    【解决方案1】:

    您可以通过CSS selector获取它:

    soup.select('div.otg-vendor-name > a.otg-vendor-name-link')[0].text
    

    或者,通过find()

    soup.find('div', class_='otg-vendor-name').find('a', class_='otg-vendor-name-link').text
    

    更新(使用requests 并提供User-Agent 标头):

    from bs4 import BeautifulSoup
    import requests
    
    url = 'http://offthegridsf.com/vendors#food'
    
    with requests.Session() as session:
        session.headers = {'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/40.0.2214.115 Safari/537.36'}
    
        session.get(url)
    
        response = session.get(url)
        soup = BeautifulSoup(response.content)
    
        print soup.select('div.otg-vendor-name > a.otg-vendor-name-link')[0].text
        print soup.find('div', class_='otg-vendor-name').find('a', class_='otg-vendor-name-link').text
    

    【讨论】:

    • 它给了我一个错误'NoneType' object is not callable - 当元素清楚地存在于网页上时它是NoneType吗?
    • @newtherapy 你能分享一个指向实际网站的链接吗?谢谢。
    • @newmotive 很有趣,这两个选项都适合我。可能是 BeautifulSoup 使用的底层解析器之间存在差异,请尝试将 soup = BeautifulSoup(web_page) 替换为 soup = BeautifulSoup(web_page, 'html.parser')soup = BeautifulSoup(web_page, 'html5lib')soup = BeautifulSoup(web_page, 'lxml')
    • 这些东西都不适合我。 :( 我想知道怎么了。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2023-02-25
    • 2012-01-21
    • 2012-01-05
    • 2012-01-09
    • 2011-12-20
    • 1970-01-01
    • 2018-11-19
    相关资源
    最近更新 更多