【发布时间】:2021-08-15 15:35:17
【问题描述】:
有点背景故事。 我正在尝试抓取 pastebin 的存档页面并仅获取粘贴的 ID。 ID 长度为 8 个字符,粘贴的示例链接如下:“https://pastebin.com/A8XGWYBu”
我目前编写的代码能够从 标记中获取所有数据,但它也会检索不必要的信息。
import requests
import re
from bs4 import BeautifulSoup
def get_recent_id():
URL = requests.get('https://pastebin.com/archive', verify=False)
href_regex = r"<a href=\"\/(.*?)\">(.*?)<\/a>"
soup = BeautifulSoup(URL.content, 'html.parser')
pastes = soup.find_all('a')
# Works good here
# prints the necessary things using the regex above
pastes_findall = re.findall(href_regex, str(pastes))
try:
for id, t in pastes_findall:
output = f"{t} -> {id}"
get_valid = r'(.*?) \-\> ([A-Za-z\d+]{8})'
final = re.findall(get_valid, output)
print(final)
except IndexError:
pass
get_recent_id()
它打破的地方是try 语句中的正则表达式。它不会返回我期望的信息,而是返回空白 [] 括号。
在try 语句中使用正则表达式的示例输出。
[]
[]
[]
[]
...
我已经在 regex101 中测试了正则表达式,它对 output 变量的输出效果很好。
我试图实现的输出应该只返回标题和粘贴 ID,并且应该如下所示:
blood sword v1.0 -> cvWdRuaV
lab2 -> eRJY9YAb
example 210526a -> A2sv2shx
2021-05-26_stats.json -> wjsmucFF
2021-05-25_stats.json -> TsXrW7ex
Flake#5595 (466999758096039936) RD -> q8tHsgMz
Untitled -> akrSbCyT
...
当 regex101 清楚地显示 2 组中有匹配项时,我不确定为什么我没有从输出中得到任何结果。如果有人能够提供帮助,我将不胜感激!
谢谢!
【问题讨论】:
-
通过正则表达式解析 html 被认为是错误的形式 - 使用 html 解析器:TH̘Ë͖́̉ ͠P̯͍̭O̚N̐Y̡ H̸̡̪̯ͨ͊̽̅̾̎Ȩ̬̩̾͛ͪ̈́̀́͘ ̶̧̨̱̹̭̯ͧ̾ͬC̷̙̲̝͖ͭ̏ͥͮ͟Oͮ͏̮̪̝͍M̲̖͊̒ͪͩͬ̚̚͜Ȇ̴̟̟͙̞ͩ͌͝S̨̥̫͎̭ͯ̿̔̀ͅ
-
你的意思是只依赖 BeautifulSoup ?
标签: python python-3.x regex web-scraping pastebin