作者热门文章
- android - RelativeLayout 背景可绘制重叠内容
- android - 如何链接 cpufeatures lib 以获取 native android 库?
- java - OnItemClickListener 不起作用,但 OnLongItemClickListener 在自定义 ListView 中起作用
- java - Android 文件转字符串
我正在用 python 编写一个程序,它执行以下操作:
我已经使用 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/
我是一名优秀的程序员,十分优秀!