首页 > 解决方案 > 蟒蛇和美丽的汤|| 在写入文件之前使用 Varible 进行正则表达式

问题描述

对于我目前遇到的问题,我希望得到一些帮助或帮助。我正在开发一个小python扫描仪作为一个项目。我当前导入的库是:

requests
BeautifulSoup
re
tld

确切的问题是关于扫描仪的“范围”。我想将 URL 传递给代码并让扫描仪从页面中获取所有锚标记,但只获取与基本 URL 相关的标记,忽略范围外的链接和子域。

这是我当前的代码,我绝不是程序员,所以请原谅草率低效的代码。

import requests
from bs4 import BeautifulSoup
import re
from tld import get_tld, get_fld

#This Grabs the URL
print("Please type in a URL:")
URL = input()

#This strips out everthing leaving only the TLD (Future scope function)
def strip_domain(URL):
    global domain_name
    domain_name = get_fld(URL)
strip_domain(URL)


#This makes the request, and cleans up the source code
def connection(URL):
        r = requests.get(URL)
        status = r.status_code
        sourcecode = r.text
        soup = BeautifulSoup(sourcecode,features="html.parser")
        cleanupcode = soup.prettify()

        #This Strips the Anchor tags and adds them to the links array
        links = []
        for link in soup.findAll('a', attrs={'href': re.compile("^http://")}):
              links.append(link.get('href'))

        #This writes our clean anchor tags to a file
        with open('source.txt', 'w') as f:            
                for item in links:
                    f.write("%s\n" % item)

connection(URL)

确切的代码问题是围绕“soup.find 中的链接”部分。我一直在尝试解析仅包含基本域的锚标记数组,即全局变量“domain_name”,以便它仅将相关链接写入源 txt 文件。

google.com accepted
google.com/file accepted
maps.google.com not written

如果有人可以帮助我或指出我正确的方向,我将不胜感激。我还认为可以将每个链接写入 source.txt 文件,然后在删除“超出范围”链接后对其进行更改,但我真的认为这样做更有益,而无需创建额外的代码。

此外,我不是最擅长正则表达式的人,但这是我帮助的人。这是一些正则表达式代码,用于捕获 http、www、https 的所有变体

(^http:\/\/+|www.|https:\/\/)

为此,我要附加

.*{}'.format(domain_name)

标签: pythonregexwebbeautifulsouppython-requests

解决方案


我提供了两种不同的情况。因为我不同意 href 值是xxx.com. 实际上你会得到三四种甚至更多的href值,比如/filefolder/file等。所以你必须将相对路径转换为绝对路径,否则你不能收集所有的url。

正则表达式:(\/{2}([w]+.)?)([a-z.]+)(?=\/?)

  1. (\/{2}([w]+.)?)匹配非主要部分从//开始
  2. ([a-z.]+)(?=\/?)匹配所有指定的字符,直到我们得到 /,我们不应该使用.*(over-match)

我的代码

import re

_input = "http://www.google.com/blabla"


all_part = re.findall(r"(\/{2}([w]+.)?)([a-z.]+)(?=\/?)",_input)[0]
_partA = all_part[2] # google.com
_partB = "".join(all_part[1:]) # www.google.com
print(_partA,_partB)

site = [
    "google.com",
    "google.com/file",
    "maps.google.com"
]
href = [
    "https://www.google.com",
    "https://www.google.com/file",
    "http://maps.google.com"
]
for ele in site:
    if re.findall("^{}/?".format(_partA),ele):
        print(ele)

for ele in href:
    if re.findall("{}/?".format(_partB),ele):
        print(ele)

推荐阅读