html - 如何在Python 3中隔离HTML页面的一部分

标签 html python-3.x text

我制作了一个简单的脚本来检索页面的源代码,但我想“隔离”ips 部分,以便可以保存到 proxy.txt 文件。有什么建议吗?

import urllib.request

sourcecode = urllib.request.urlopen("https://www.inforge.net/xi/threads/dichvusocks-us-15h10-pm-update-24-24-good-socks.455588/")
sourcecode = str(sourcecode.read())
out_file = open("proxy.txt","w")
out_file.write(sourcecode)
out_file.close()

最佳答案

我在您的代码中添加了几行,唯一的问题是 UI 版本(检查页面源代码)被添加为 IP 地址。

import urllib.request
import re

sourcecode = urllib.request.urlopen("https://www.inforge.net/xi/threads/dichvusocks-us-15h10-pm-update-24-24-good-socks.455588/")
sourcecode = str(sourcecode.read())
out_file = open("proxy.txt","w")
out_file.write(sourcecode)
out_file.close()

with open('proxy.txt') as fp:
    for line in fp:
        ip = re.findall('(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', line)

for addr in ip:
    print(addr)

更新: 这就是您要找的,BeatifulSoup 可以使用 CSS 类从页面中仅提取我们需要的数据,但是它需要与 pip 一起安装。您不需要将页面保存到文件中。

from bs4 import BeautifulSoup
import urllib.request
import re

url = urllib.request.urlopen('https://www.inforge.net/xi/threads/dichvusocks-us-15h10-pm-update-24-24-good-socks.455588/').read()
soup = BeautifulSoup(url, "html.parser")

# Searching the CSS class name
msg_content = soup.find_all("div", class_="messageContent")

ips = re.findall('(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})\.(?:[\d]{1,3})', str(msg_content))

for addr in ips:
    print(addr)

关于html - 如何在Python 3中隔离HTML页面的一部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38420505/

相关文章:

javascript - 动态创建的 div 中未显示数组元素?

javascript - 可折叠不工作 [包含 JSFiddle 演示]

html - 无法更改 margin

python - 程序不返回任何值而不返回值

javascript - Colossal Caves Adventure - 使用 javascript 访问数据源

c# - 将文字添加到图像并保存

javascript - 音频 HTML5 自动播放 WebWorks

Python代码: Information on Execution Trace of loops/conditionals

python - 如何在 PyQt5 GUI 中显示 Folium map ?

php - mysql 列的最大长度并确保我不会使用 utf8_unicode_ci - PHP 超过该限制?