gpt4 book ai didi

python - 如何将 Python 的 urllib2.urlopen() 转换为文本?

转载 作者:可可西里 更新时间:2023-11-01 13:51:12 26 4
gpt4 key购买 nike

我正在用 python 编写一个程序,它执行以下操作:

  • 从网络获取信息。
  • 将其放在 .txt 文件中。

我已经使用 urllib2.urlopen() 给我 HTML 代码,但我想要页面的信息。我说:

urllib2.urlopen() 获取 HTML。但我想要写在文本上的 HTML,我不想要 HTML 代码!!

我目前的计划:

import urllib2
import time
url = urllib2.urlopen('http://www.dev-explorer.com/articles/using-python-httplib')
html = url.readlines()
for line in html:
print line

time.sleep(5)

最佳答案

您必须使用某种方法来读取您打开的内容:

url = urllib2.urlopen('someURL')
html = url.readlines()
for line in html:
#At this level you already have a str in 'line'
#do something

还有其他方法:read, readline

编辑:

正如我在此线程中的一条评论中所说,也许您需要使用 BeautifulSoup报废你想要的东西。所以,我认为这已经解决了here .

你必须安装 BeautifulSoup:

pip install BeautifulSoup

然后你必须按照示例中的内容进行操作:

from bs4 import BeautifulSoup
import urllib2
import re

html = urllib.urlopen('someURL').read()
soup = BeautifulSoup(html)
texts = soup.findAll(text=True)

def visible(element):
if element.parent.name in ['style', 'script', '[document]', 'head', 'title']:
return False
elif re.match('<!--.*-->', str(element)):
return False
return True

visible_texts = filter(visible, texts)

如果你对 ascii 字符有一些问题,你必须在 visible 函数中将 str(element) 更改为 unicode(element)。

关于python - 如何将 Python 的 urllib2.urlopen() 转换为文本?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34157599/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com