【发布时间】:2018-12-16 06:03:23
【问题描述】:
我在 python 中结合re 模块编写了一个脚本,以从网页中获取不同问题的标题。我的意图是不使用BeautifulSoup 并且仍然能够解析标题。我使用模式的方式可以做到这一点。但是,输出看起来并不那么好。我怎样才能只得到问题标题而没有其他任何东西。
这是我的尝试(使用re.search()):
import requests
import re
link = "https://stackoverflow.com/questions/tagged/web-scraping"
res = requests.get(link).text
for item in res.splitlines():
matchitem = re.search(r'hyperlink">(How.+)</a>',item)
if matchitem:
print(matchitem.group())
我得到的输出(从几个中):
hyperlink">How to use Selenium check the checkbox lists?</a>
我希望得到的是这样的:
How to use Selenium check the checkbox lists?
我对正则表达式很陌生。所以,如果我的问题不适合成为问题,我会提前道歉。
【问题讨论】:
-
使用正则表达式解析 HTML 代码最初是个坏主意。为什么你不想使用 BeautifulSoup?您也可以检查恕我直言更好的选择 - lxml.html
标签: python regex python-3.x web-scraping