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

RDP*_*DPD 1 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)
Run Code Online (Sandbox Code Playgroud)

Mat*_*son 5

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

soup.title.string
Run Code Online (Sandbox Code Playgroud)

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

for tag in soup.findAll():
    try:
        print(tag['title'])
    except KeyError:
        pass
Run Code Online (Sandbox Code Playgroud)

这将打印页面中标签的所有标题.我们查看所有标签,尝试打印其标题值,如果没有,我们将得到一个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)
Run Code Online (Sandbox Code Playgroud)