【问题标题】:Extract table data from website using Python使用 Python 从网站中提取表数据
【发布时间】:2019-04-17 02:38:09
【问题描述】:

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

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

我正在使用正则表达式方法从表格中获取详细信息。

######

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")
######

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

【问题讨论】:

  • 如果你使用bs4。这项工作可以更快、更容易地完成。此外,您在此站点中不需要硒。

标签: python regex beautifulsoup python-requests


【解决方案1】:

我不建议你用正则表达式抓取数据,因为它可以由bs4完成,如果你建立一个正则表达式来完成你需要很长时间和复杂的条件。

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")

【讨论】:

    猜你喜欢
    • 2017-01-23
    • 2015-08-26
    • 1970-01-01
    • 2020-06-14
    • 2017-11-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 2021-10-29
    相关资源
    最近更新 更多