使用Python和BeautifulSoup访问网页中标签的title属性

时间:2015-04-16 16:10:34

标签: python beautifulsoup bs4

我是Python的新手,我正在尝试从特定网址中检索所有标题,但我无法这样做。代码编译没有任何错误,但仍然没有得到输出。

import requests
import sys
from bs4 import BeautifulSoup

def test_function(num):
    url = "https://www.zomato.com/chennai/restaurants?buffet=1&page=" +       
    str(num)
    source_code = requests.get(url) 
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for link in soup.findAll('title'):
        print(link)
test_function(1)

2 个答案:

答案 0 :(得分:5)

要获取页面标题,您只需使用:

soup.title.string

但是,似乎不是实际想要页面标题,而是需要包含标题的任何标记的属性。如果您希望获得每个标记的title属性(如果存在),那么您可以这样做:

for tag in soup.findAll():
    try:
        print(tag['title'])
    except KeyError:
        pass

这将打印页面中标签的所有标题。我们查看所有标签,尝试打印其标题值,如果没有,我们将获得KeyError,然后我们不对错误做任何事情!

还存在未向请求传递用户代理的问题。如果不这样做,该网站将给出500错误。我在代码中添加了以下内容。

使用您的代码

import requests
import sys
from bs4 import BeautifulSoup

HEADERS = {"User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64; rv:20.0) Gecko/20100101 Firefox/20.0"}

def test_function(num):
    url = "https://www.zomato.com/chennai/restaurants?buffet=1&page=" +       
        str(num)
    source_code = requests.get(url, headers=HEADERS) 
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text)
    for tag in soup.findAll():
        try:
            print(tag['title'])
        except KeyError:
            pass

test_function(1)

答案 1 :(得分:1)

您需要添加标题以获取响应200,然后执行与此相同的操作。

def test_function(num):
    url = "https://www.zomato.com/chennai/restaurants"
    params = {'buffet': 1, 'page': num}
    header = {'Accept-Encoding': 'gzip, deflate, sdch',
              'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
              'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_10_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.118 Safari/537.36'}
    r = requests.get(url, params=params, headers=header)
    plain_text = r.text
    soup = BeautifulSoup(plain_text)
    for link in soup.findAll('title'):
        print(link.text)


test_function(1)
Restaurants in Chennai serving Buffet - Zomato