根据特定标签在Web上刮取并打印所有名称和标签

问题描述 投票:-2回答:1

我的HTML链接上的所有名称都有一个标签好吗? (我使用漂亮的汤)如果他们的标签==,我想废弃并打印所有带有标签的名称 '特定字符串'好吗?

我的班级名称是div

我的id name ='name'

我的id标签='标签'

我的代码是这样的:

from bs4 import BeautifulSoup
import requests

r = requests.get('https://aaaaaaaaa.org/plus')
soup = BeautifulSoup(r.text, 'html.parser')
res = soup.find_all(id={'name', 'tag'})
for item in res:
    print(item.text.strip())

我的输出是这样的:

General English: Intermediate
bbb
General English: Elementary
AAAAAAAAAAA
General English: Intermediate Plus
bbbbbbb
General English: Beginner
ggg
TOEFL iBT: Listening and Speaking
bbbbbbbb
TOEFL iBT: Reading
AAAAAAAAAAA
Grammar for IELTS
AAAAAAAAAAA

但我想只要标签== AAAAAAAAAAA给我标签的标签好吗?如下:

General English: Elementary
AAAAAAAAAAA
TOEFL iBT: Reading
AAAAAAAAAAA
Grammar for IELTS
AAAAAAAAAAA

请帮助我,谢谢你的帮助:)

python web-scraping beautifulsoup python-requests
1个回答
-1
投票

我认为最好的方法是使用xpath。您可以使用lxml库。

import lxml.html
import lxml.etree

def html_to_root(html):
    html_parser = lxml.etree.HTMLParser(encoding='utf-8')
    return lxml.etree.HTML(html, parser=html_parser)

 html_tree = html_to_root(resp.content)

 division_you_want = html_tree.xpath('xpath')
© www.soinside.com 2019 - 2024. All rights reserved.