【发布时间】:2021-03-08 17:31:50
【问题描述】:
我是 Python 新手, 我想提取放置在 Divs 中的 标签内的所有标题/s。 它可能有 0 个标题或多达 100 个。
它是子 DIV <div class="Shl zI7 iyn Hsu">,其中包含 标记和标题。
这是第一个包含所有子 DIV 的主 DIV 代码:
<div class="Eqh F6l Jea k1A zI7 iyn Hsu"><div class="Shl zI7 iyn Hsu"><a data-test-id="search-guide"
href="" title="Search for "living room colors""><div class="Jea Lfz XiG fZz gjz qDf zI7 iyn
Hsu" style="white-space: nowrap; background-color: rgb(162, 152, 139);"><div class="tBJ dyH iFc MF7
erh tg7 IZT mWe">Living</div></div></a>
在上面的例子中,我想获得“客厅颜色”而不是 title= 前面的所有内容, 我想我以后可以有一些 RegEx,但我有从 HTML 解析中获取标题的问题。
我尝试过以下 Python:
import requests
from bs4 import BeautifulSoup
url = "https://www.pinterest.com/search/pins/?q=room%20color"
get_url = requests.get(url)
get_text = get_url.text
soup = BeautifulSoup(get_text, "html.parser")
DivTitle = soup.select('a.Shl.zI7.iyn.Hsu')[0].text.strip()
print(DivTitle)
我得到:IndexError:列表索引超出范围
当我搜索上述关键字时,搜索结果中出现了不止一个标题(建议关键字)。
感谢您的帮助。
编辑: 好的,我得到了这个工作,但我试图让它从 URL 解析而不是粘贴我的代码:
这是我使用的部分:
import requests
vgm_url = 'https://www.pinterest.com/search/pins/?q=skin%20care'
html_text = requests.get(vgm_url).text
soup = BeautifulSoup(html_text, 'html.parser')
但我什么也没得到,也没有错误。
【问题讨论】:
标签: python html html-parsing title