使用BeautifulSoup解析HTML时遇到问题
16lz
2021-01-22
I'm having trouble parsing some html using beautifulsoup.
我在使用beautifulsoup解析一些html时遇到问题。
In this piece of HTML for example, I want to extract the Target Text. More HTML in the HTML code is like this so I want to extract all the Target Texts. I also want to extract the "tt0082971" and put that number and the Target Text in two rows of a tab-delimted file. The numbers after 'tt' change for every instance of Target Text.
例如,在这篇HTML中,我想提取目标文本。 HTML代码中的更多HTML是这样的,所以我想提取所有目标文本。我还想提取“tt0082971”并将该数字和目标文本放在制表符分隔文件的两行中。 'tt'之后的数字为目标文本的每个实例更改。
<td class="target">
<span class="wlb_wrapper" data-caller-name="search" data-size="small" data-tconst="tt0082971">
</span>
<a href="/target/tt0082971/">
Target Text 1
</a>
1 个解决方案
#1
0
BeautifulSoup.select
accepts CSS Selectors:
BeautifulSoup.select接受CSS选择器:
>>> from bs4 import BeautifulSoup
>>>
>>> html = '''
... <td class="target">
... <span class="wlb_wrapper" data-caller-name="search" data-size="small" data-tconst="tt0082971">
... </span>
... <a href="/target/tt0082971/">
... Target Text 1
... </a>
... </td>
... '''
>>> soup = BeautifulSoup(html)
>>> for td in soup.select('td.target'):
... span = td.select('span.wlb_wrapper')
... if span:
... print span[0].get('data-tconst') # To get `tt0082971`
... print td.a.text.strip() # To get target text
...
tt0082971
Target Text 1
更多相关文章
- 使用下一个div中的文本设置“下一个”按钮的文本
- HTML基础 img标签alt属性 当图片加载失败的时候显示为文本
- 【WEB基础】HTML & CSS 基础入门(3)段落及文本
- 为什么v-align中的将文本放在图像下面
- 如何在窗体上布局文本和输入以适应特定的宽度?
- 如何使用JavaScript修改基于onclick的文本?
- 去除Chrome浏览器文本框边缘的黄线
- 如何设置div的样式以使其与文本一起运行?
- 用正则表达式剔除文本里面HTML标记