Beautifulsoup 在div中获得元素名称的漂亮汤

Beautifulsoup 在div中获得元素名称的漂亮汤,beautifulsoup,html-parsing,Beautifulsoup,Html Parsing,我第一次使用BeautifulSoup,我试图获取网页中特定元素的值 例如,在此代码段中: <div class="otg-vendor-name"><a class="otg-vendor-name-link" href="http://www.3brotherskitchen.com" target="_blank">3 Brothers Kitchen</a></div> 您可以通过以下方式获得: 或者,通过: 使用请求和提供用户代

我第一次使用BeautifulSoup,我试图获取网页中特定元素的值

例如,在此代码段中:

<div class="otg-vendor-name"><a class="otg-vendor-name-link"     href="http://www.3brotherskitchen.com" target="_blank">3 Brothers Kitchen</a></div>
您可以通过以下方式获得:

或者,通过:

使用请求和提供用户代理标头进行更新:


它给我的错误是“非类型”对象不可调用-当元素明显存在于网页上时,它是如何非类型的?@newfander你能分享一个实际网站的链接吗?谢谢。@newfander很有趣,两种选择都适合我。可能是BeautifulSoup使用的底层解析器之间存在差异,请尝试用soup=BeautifulSoupweb\u页面、“html.parser”或soup=BeautifulSoupweb\u页面、“html5lib”或soup=BeautifulSoupweb\u页面“lxml”替换soup=BeautifulSoupweb\u页面。这些东西对我都不起作用我不知道怎么了。
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
soup.select('div.otg-vendor-name > a.otg-vendor-name-link')[0].text
soup.find('div', class_='otg-vendor-name').find('a', class_='otg-vendor-name-link').text
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