python 搜索html,使用python(3.3.1)在html源代码中搜索字符串

我正在开发一个从网页获取信息的项目.

在html源代码中我有以下内容:

Resultado de Busca:Foram encontrados 264 casais

我需要得到“encontrados”和“casais”之间的数字

无论如何在Python中有这样做吗?我应该使用什么字符串函数?我想在这种情况下避免使用正则表达式.

import urllib.request

f = urllib.request.urlopen("http://listadecasamento.fastshop.com.br/ListaCasamento/ListaCasamentoBusca.aspx?Data=2013-06-07")

s = f.read()

print(s.split())

到目前为止我得到了这个,但现在我找不到我需要的号码了.

import urllib.request

f = urllib.request.urlopen("http://listadecasamento.fastshop.com.br/ListaCasamento/ListaCasamentoBusca.aspx?Data=2013-06-07")

s = f.read()

num = int(s[s.index("encontrados")+len("encontrados"):s.index("casais")])

这给我下面的错误

TypeError:类型str不支持缓冲区API

解决方法:

我建议使用像Beautiful Soup这样的库,如果它是你要解析的HTML.不需要正则表达式.

编辑

使用刚刚添加的URL,这是获取HTML对象的示例代码:

import BeautifulSoup

import re

import urllib

data = urllib.urlopen('http://listadecasamento.fastshop.com.br/ListaCasamento/ListaCasamentoBusca.aspx?Data=2013-06-07').read()

soup = BeautifulSoup.BeautifulSoup(data)

element = soup.find('span', attrs={'class': re.compile(r".*\btxt_resultad_busca_casamento\b.*")})

print element.text

这将在页面上找到具有类txt_resultad_busca_casamento的HTML span元素,我相信这是您要提取的数据.从那里你可以解析.text属性来获得你感兴趣的确切数据.

编辑2

哎呀,刚才意识到使用正则表达式……看起来BeautifulSoup中的类匹配并不完美!这条线应该起作用,至少在网站更改HTML之前:

element = soup.find('div', attrs={'id': 'ctl00_body_uppBusca'}).find('span')

标签:python,string,split

来源: https://codeday.me/bug/20190825/1720893.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值