使用Python从网站提取表数据

2024-09-29 00:19:13 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试获取与用户试图访问的任何网站相关的信息。为了阻止任何恶意网站访问,我需要像黑名单状态,IP地址,服务器位置等详细信息。我从URLVOID网站得到这个。<;https://www.urlvoid.com/scan/>

我得到了以下表格格式的结果,并试图在spyder中获取相同的结果。 See the Table

我使用regex方法从表中获取详细信息。在

######

import httplib2 
import re
def urlvoid(urlInput):                
    h2 = httplib2.Http(".cache")
    resp, content2 = h2.request(("https://www.urlvoid.com/scan/" + urlInput), "GET")
    content2String = (str(content2))
    rpderr = re.compile('\<div\sclass\=\"error\"\>', re.IGNORECASE)
    rpdFinderr = re.findall(rpderr,content2String)
    if "error" in str(rpdFinderr):
        ipvoidErr = True
    else:
        ipvoidErr = False
    if ipvoidErr == False:

        rpd2 = re.compile('(?<=Server Location</span></td><td>)[a-zA-Z0-9.]+(?=</td></tr>)')
        rpdFind2 = re.findall(rpd2,content2String)
        rpdSorted2=sorted(rpdFind2)

    return rpdSorted2

urlvoid("google.com")
######

然而,它的效率不高,而且这个正则表达式并不适用于所有的网站。有没有更简单的方法来获取所有这些信息?在


Tags: 方法httpsimportrecom信息scan网站
1条回答
网友
1楼 · 发布于 2024-09-29 00:19:13

我不建议您使用regex来获取数据,因为它可以通过bs4来完成,并且如果您构建一个regex来完成,则需要较长的时间和复杂的条件。在

import requests
from bs4 import BeautifulSoup,NavigableString
import re

def urlvoid(urlInput):
    url = "https://www.urlvoid.com/scan/" + urlInput
    res = requests.get(url)
    text = res.text
    soup = BeautifulSoup(text,"lxml").find("table",class_="table table-custom table-striped")
    all_tr = soup.find_all("tr")
    value = { tr.find_all("td")[0].text : 
                tr.find_all("td")[1].text.replace("\xa0","")
                for tr in all_tr}
    print(value)

urlvoid("google.com")

相关问题 更多 >