Python 正则表达式匹配行如果以什么结尾?

标签 python regex

这就是我要抓取的内容:

        <p>Some.Title.html<br />
<a href="https://www.somelink.com/yep.html" rel="nofollow">https://www.somelink.com/yep.html</a><br />
Some.Title.txt<br />
<a href="https://www.somelink.com/yeppers.txt" rel="nofollow">https://www.somelink.com/yeppers.txt</a><br />

我尝试了以下几种变体:

match = re.compile('^(.+?)<br \/><a href="https://www.somelink.com(.+?)">',re.DOTALL).findall(html)

我希望匹配带有和不带“p”标签的行。 “p”标签只出现在第一个实例中。对 python 很糟糕,所以我很生疏,在这里和谷歌搜索过,似乎没有什么是完全一样的。谢谢你的帮助。真的很感谢我在遇到困难时得到的帮助。

期望的输出是一个索引:

<a href="Some.Title.html">http://www.SomeLink.com/yep.html</a>
<a href="Some.Title.txt">http://www.SomeLink.com/yeppers.txt</a>

最佳答案

使用 Beautiful soup 和 requests 模块非常适合这样的事情,而不是上面评论者提到的正则表达式。

import requests
import bs4

html_site = 'www.google.com' #or whatever site you need scraped
site_data = requests.get(html_site) # downloads site into a requests object
site_parsed = bs4.BeautifulSoup(site_data.text) #converts site text into bs4 object
a_tags = site_parsed.select('a') #this will select all 'a' tags and return list of them

这只是一个简单的代码,它将从 html 站点中选择所有标签并将它们存储在一个列表中,其格式如上所示。我建议检查 here有关 bs4 和 here 的精彩教程对于实际文档。

关于Python 正则表达式匹配行如果以什么结尾?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45406760/

相关文章:

python - 测试 #2 失败。错误的答案

python - 如何将 Pandas 数据框字符串值转换为数值

python - 使用 pyautogui 将鼠标光标移动到第二台显示器

python - 将 PyGame 2 Axis 操纵杆 float 转换为 360 度

python - 当 __init__.py 破坏 pyinstaller 时如何正确导入文件

java - java中反转字符串而不改变空格

regex - Grep 模式与多行与操作

javascript - 将标签转换为 html 实体

python - 为什么这不是固定宽度的图案?

python - 如何在 Windows 上用 Python (3) 读取/写入文件而不引入回车符?