我正在使用beautifulSoup从网站中提取数据。每当您重新加载页面时,该网站上的文本都会更改,因此基本上,我希望能够将重点放在类名称上作为静态变量,因为文本是动态的。
import requests
from bs4 import BeautifulSoup
url = 'xxxxxxxxxxx'
r = requests.get(url)
soup = BeautifulSoup(r.content, 'html.parser')
class2 = soup.find_all(True, class_="template_title")
print (class2)
打印出来的内容
<td align="left" class="template_title" height="50" valign="bottom" width="535"><div style="padding-bottom:9px;">4</div></td>
当页面重新加载时,我仍然将重点放在该区域上,但是我不知道如何仅打印文本(在这种情况下为:4)
一旦解决了这个问题,我还有另一个问题:如果该类包含多个标签,是否有办法获取更多静态数据,以确保它只打印我在搜索的文本,而不是其他文本?(我上过课,但是我也可以使用height =“ 50” valign =“ bottom” width =“ 535”吗?)
您可以使用text
或string
属性的元素。
elems = soup.find_all(True, class_='template_title')
print([elem.string for elem in elems])
# prints `['4']` for the given html snippet
根据需要指定更多属性:
elems = soup.find_all(True, class_='template_title',
height='50', valign='bottom', width='535')
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句