使用 Python 阅读网站的每一行
Read every line from a website with Python
我希望在有行的情况下阅读网页上的每一行。到目前为止,我有下面的代码。我无法让它为每一行的值分配临时值,我希望使用正则表达式来检查该行是否符合特定格式。
#!/usr/bin/python
import urllib2
import re
#imported urllib to collect the data. imported re for regular expressions to test format.
#creating our output file
f=open("OUIoutput.txt", "w+")
#opening a file like object using urllib
webpage= urllib2.urlopen("https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf")
#string used to store the output
str1=""
#string used to store current line
temp=""
#while loop to read in the data for every line.INCORRECT FOR LOOP BASIC PLACEHOLDER IN THE CODE
for i in (60,500):
temp=webpage.readline(i)
if re.search("\w\w:\w\w:\w\w", temp):
str1+=temp
f.write(str1)
您可以使用单次调用 re.findall
,利用 MULTILINE 标志:
import requests
import re
pattern = re.compile(ur'^.*\w\w:\w\w:\w\w.*$', re.M)
url = "https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf"
webpage = requests.get(url)
print u'\n'.join(pattern.findall(webpage.text)).encode('utf-8')
根据您的评论回答:
您不需要为此使用范围。 readlines() 函数就是你要找的。
for line in webpage.readlines():
#do your work here
我希望在有行的情况下阅读网页上的每一行。到目前为止,我有下面的代码。我无法让它为每一行的值分配临时值,我希望使用正则表达式来检查该行是否符合特定格式。
#!/usr/bin/python
import urllib2
import re
#imported urllib to collect the data. imported re for regular expressions to test format.
#creating our output file
f=open("OUIoutput.txt", "w+")
#opening a file like object using urllib
webpage= urllib2.urlopen("https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf")
#string used to store the output
str1=""
#string used to store current line
temp=""
#while loop to read in the data for every line.INCORRECT FOR LOOP BASIC PLACEHOLDER IN THE CODE
for i in (60,500):
temp=webpage.readline(i)
if re.search("\w\w:\w\w:\w\w", temp):
str1+=temp
f.write(str1)
您可以使用单次调用 re.findall
,利用 MULTILINE 标志:
import requests
import re
pattern = re.compile(ur'^.*\w\w:\w\w:\w\w.*$', re.M)
url = "https://code.wireshark.org/review/gitweb?p=wireshark.git;a=blob_plain;f=manuf"
webpage = requests.get(url)
print u'\n'.join(pattern.findall(webpage.text)).encode('utf-8')
根据您的评论回答:
您不需要为此使用范围。 readlines() 函数就是你要找的。
for line in webpage.readlines():
#do your work here