【问题标题】:How to search for matched string then extract the string after it and a colon如何搜索匹配的字符串然后提取它后面的字符串和一个冒号
【发布时间】:2017-09-27 16:06:55
【问题描述】:

我是 Python 和网络抓取的新手,所以如果问题太基本,我深表歉意!

我想从以下示例 BeautifulSoup 对象中提取“分数”和“评分”(评分)

import bs4
import re
text = '<html><body>{"count":1,"results":[{"score":"2-1","MatchId":{"number":"889349"},"name":"Match","rating":{"rate":9.0}}],"performance":{"comment":{}}}</body></html>'
page = bs4.BeautifulSoup(text, "lxml")
print type(page)

我已经尝试了这些,但没有任何显示(只是空白 [])

tmp = page.find_all(text=re.compile("score:(.*)"));
print(tmp)

tmp = page.findAll("score");
print(tmp)

我找到了这个similar question,但它给了我错误

tmp = page.findAll(text = lambda(x): x.lower.index('score') != -1)
print(tmp)

AttributeError: 'builtin_function_or_method' object has no attribute 'index'

我做错了什么?提前致谢!

【问题讨论】:

  • 尝试使用x.lower() 而不是x.lower。
  • 完全使用JSON 解析器!
  • 感谢您的宝贵时间!

标签: python regex web-scraping beautifulsoup pattern-matching


【解决方案1】:

这是实现turducken 协议的三分之二。您可以使用 beautifulsoup 查找正文并使用 json 对其进行解码。然后你有一些 python 字典和列表要通过。

>>> import json
>>> import bs4
>>> import re
>>> text = '<html><body>{"count":1,"results":[{"score":"2-1","MatchId":{"number":"889349"},"name":"Match","rating":{"rate":9.0}}],"performance":{"comment":{}}}</body></html>'
>>> page = bs4.BeautifulSoup(text, "lxml")
>>> 
>>> data = json.loads(page.find('body').text)
>>> for result in data["results"]:
...     print(result["score"], result["rating"]["rate"])
... 
2-1 9.0
>>> 

【讨论】:

  • 像魅力一样工作!今天学了点儿新东西。谢谢@tdelaney!
猜你喜欢
  • 2018-05-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-14
  • 1970-01-01
  • 2023-03-08
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多