gpt4 book ai didi

python - 如何在 Python 中提取

之间的文本?
转载 作者:搜寻专家 更新时间:2023-10-31 23:03:01 24 4
gpt4 key购买 nike

我无法在 <h1> 之间提取文本和 </h1> .

请帮帮我。

我的代码是:

import bs4
import re
import urllib2

url2='http://www.flipkart.com/mobiles/pr?sid=tyy,4io&otracker=ch_vn_mobile_filter_Top%20Brands_All#jumpTo=0|20'
htmlf = urllib2.urlopen(url2)
soup = bs4.BeautifulSoup(htmlf)
#res=soup.findAll('div',attrs={'class':'product-unit'})
for res in soup.findAll('a',attrs={'class':'fk-display-block'}):
suburl='http://www.flipkart.com/'+res.get('href')
subhtml = urllib2.urlopen(suburl)
subhtml = subhtml.read()
subhtml = re.sub(r'\s\s+','',subhtml)
subsoup=bs4.BeautifulSoup(subhtml)
res2=subsoup.find('h1',attrs={'itemprop':'name'})
if res2:
print res2

输出:

<h1 itemprop="name">Moto G</h1>
<h1 itemprop="name">Moto E</h1>
<h1 itemprop="name">Moto E</h1>

但我想要这个:

Moto G
Moto E
Moto E

最佳答案

在任何 HTML 标签上,执行 get_text() 都会给出与标签关联的文本。所以,你只需要使用 get_text()在 res2 上。即,

if res2:
print res2.get_text()

PS:作为旁注,我认为代码中的这一行 subhtml = re.sub(r'\s\s+','',subhtml)是一个昂贵的操作。如果你所做的只是摆脱多余的空间,你可以这样做:

if res2:
print res2.get_text().strip()

关于python - 如何在 Python 中提取 <h1></h1> 之间的文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25497403/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com