【问题标题】:Extract text from img tag of bs4.element.Tag从 bs4.element.Tag 的 img 标签中提取文本
【发布时间】:2019-09-22 16:39:32
【问题描述】:

我有以下问题要问。

我有一个 bs4.element.Tags 列表,就像这张图片的列表

正如你所看到的,有很多元素都有标签“a href="/title/...">。但是,我不想保留所有这些。我只想要那些从<img> 标记开始。我该如何实现?

其次,当我只保留这些元素时

我只想保留标题标签内的单词。比如下图中要保留“img title="Gravity”这样就只有Gravity这个词了。

HTML 文档链接: HTML Documents for each movie

代码

from tqdm import tqdm
with open('requests_list_dummy.pkl', 'rb') as f:
    requests_list_dummy = pickle.load(f)

souplist = []

for i in tqdm(requests_list_dummy):
    souplist.append(BeautifulSoup(i.text))

souplist_dummy = souplist

# phase 1

phase_1 = []

for i in tqdm(souplist_dummy):
    phase_1.append(i.find_all('div', {'class':'article', 'id': 'titleRecs'}))

# -----------------------------------------------------------------------------------

# phase 2

phase_2 = []

import re
r_one = re.compile(".*title")

for i in tqdm(phase_1):
    for j in i:
        phase_2.append(j.find_all('img'))

# -----------------------------------------------------------------------------------

# # phase 3

phase_3 = []

for i in tqdm(range(len(phase_2))):
    phase_3.append(list(map(lambda x: x, phase_2[i][0:12])))

# # phase 4

phase_4 = []

for i in tqdm(phase_3):
    for j in i:
        phase_4.append(j.find_all('title'))

【问题讨论】:

  • 你能发布实际的 html 而不是图片吗?
  • 你的意思是a>img[title]
  • @JackFleeting 我没有 HTML 代码,因为它在 Python Notebook 中。
  • @mplungjan 我尝试调用 .find_all('img', {'title'})..但没有结果
  • 不能直接复制粘贴吗?

标签: python html image beautifulsoup tags


【解决方案1】:

您可以尝试以下要求 bs4 4.7.1+ 并使用 :has 指定您想要带有 img 子级的 a 标记,然后相邻的兄弟组合器获得下一个 img 并添加属性 = 值选择器以确保 href 包含特定的子字符串和 title 属性。如果您知道总会有一个 title 属性,您可以从选择器中删除它。

titles = [i['title'] for i in soup.select("a:has(img) + [href*='/title/tt'][title]")]

【讨论】:

    猜你喜欢
    • 2021-02-27
    • 2022-11-25
    • 2019-12-15
    • 1970-01-01
    • 1970-01-01
    • 2021-05-20
    • 1970-01-01
    • 1970-01-01
    • 2021-11-29
    相关资源
    最近更新 更多