python3代码,从网页源代码中仅检索一行特定代码
在我的代码中,我使用的是urlopen,但它会获取整个网页。是否可以仅检索网页源代码的一个特定行号以优化我的程序 例如,我想打印此链接源代码中的行号135python3代码,从网页源代码中仅检索一行特定代码,python,url,python-3.x,urlopen,Python,Url,Python 3.x,Urlopen,在我的代码中,我使用的是urlopen,但它会获取整个网页。是否可以仅检索网页源代码的一个特定行号以优化我的程序 例如,我想打印此链接源代码中的行号135www.ncbi.nlm.nih.gov/snp/?term=273898673?term=273898673 mycode: from urllib.request import urlopen query="www.ncbi.nlm.nih.gov/snp/?term=273898673?term=273898673" data=urlop
www.ncbi.nlm.nih.gov/snp/?term=273898673?term=273898673
mycode:from urllib.request import urlopen
query="www.ncbi.nlm.nih.gov/snp/?term=273898673?term=273898673"
data=urlopen(query)
html = data.read()
codec = data.info().get_param('charset', 'utf8')
data = html.decode(codec)
print (data)
我可以执行任何urlopen()自定义吗?P.S我有python 3.X
您可以使用enumerate获取特定行号,而无需立即读取内存中的所有内容:
import urllib.request
response = urllib.request.urlopen('http://www.ncbi.nlm.nih.gov/snp/?term=273898673?term=273898673')
for line_number, line in enumerate(response):
# Because this is 0-index based
if line_number == 134:
print line
# Stop reading
elif line_number > 134:
break
不,这是不可能的。web服务器将始终为整个文档提供服务,因此您必须解析获取的文本。