【问题标题】:Can't capture href tag content with regex first time第一次无法使用正则表达式捕获 href 标记内容
【发布时间】:2021-04-05 10:39:30
【问题描述】:

我想通过在href html 标记上使用正则表达式来抓取网站的外部链接和路径。

但我不知道是否有比我的代码更简单的方法:

import requests
import re

target_url = ("http://testphp.vulnweb.com/")

response = requests.get(target_url)
res = re.findall('href\=\"[\w.:/]+\"', response.content.decode("utf-8"))

for i in res:
    patt = re.compile("\"[.:/\w]+\"")
    not_raw = re.findall(patt, i)
    raw = re.findall("[.:/\w]+", not_raw[0])
    print(raw)

有没有办法,而不是使用正则表达式 3 次,从 href 标记中选择路径和链接而不捕获它? 我的意思是res 变量输出是这样的:

href="https://www.acunetix.com/vulnerability-scanner/"

我可以使用正则表达式来获取 res 变量中的 URL,如下所示?

https://www.acunetix.com/vulnerability-scanner/

【问题讨论】:

  • 可能是因为通常不鼓励使用正则表达式抓取 HTML。使用 BeautifulSoup。

标签: python python-3.x regex web-scraping


【解决方案1】:

是的,您可以使用“捕获”和“非捕获”匹配。示例:

re.findall(r'(?:href=")([^\"]+)(?:")', response.content.decode("utf-8"))

(?:href=") 中的?: 表示这部分不会作为匹配字符串的一部分返回。

来自https://docs.python.org/3/library/re.html

(?:...) 常规括号的非捕获版本。匹配括号内的任何正则表达式,但组匹配的子字符串在执行匹配后无法检索或稍后在模式中引用。

【讨论】:

    【解决方案2】:

    使用正则表达式解析HTML 是一个糟糕的选择。请参阅this 了解原因。

    要获取所有href 属性,请使用HTML 库,例如BeautifulSoup,然后试试这个:

    import requests
    from bs4 import BeautifulSoup
    
    response = requests.get("http://testphp.vulnweb.com/").content
    soup = BeautifulSoup(response, "html.parser").find_all("a", href=True)
    href_ = [a["href"] for a in soup if "http" in a["href"]]
    print("\n".join(href_))
    
    

    输出:

    https://www.acunetix.com/
    https://www.acunetix.com/vulnerability-scanner/
    http://www.acunetix.com
    https://www.acunetix.com/vulnerability-scanner/php-security-scanner/
    https://www.acunetix.com/blog/articles/prevent-sql-injection-vulnerabilities-in-php-applications/
    http://www.eclectasy.com/Fractal-Explorer/index.html
    http://www.acunetix.com
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-15
      • 2012-04-04
      • 1970-01-01
      • 1970-01-01
      • 2011-10-28
      相关资源
      最近更新 更多