编写爬虫程序时,常见的操作是从页面上解析出url,然后深度(或广度)探寻,然而有时候解析出来的文本含有一些杂质,需要一些过滤后才是我们想要的url。

Python:如何判断一个url是以http开头的?

比如一个文本test.txt,里面的内容为:

http://www.sogou.com
this is a url
this is http://www.sogou.com address

1. 简单的判断包含

#encoding: utf-8
 
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 if "http" in line:
 print(line)

输出为:

http://www.sogou.com
this is http://www.sogou.com address

2. 正则匹配

获取以http开头:

#encoding: utf-8
import re
with open("test.txt", "r") as f:
content = f.readlines()
for line in content:
 r = re.match("http", line)
 if r != None:
 print(line)

输出为:

http://www.sogou.com

re.match, 从开头匹配字符串,如果匹配到返回匹配到的对象。没有匹配到返回None。

3. 调用python自带函数

判断开头:

#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.startswith("http"):
 print(line)

输出为:

http://www.sogou.com

判断结尾:

#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.replace("\n","").endswith("com"):
 print(line)

这里要注意的是,每行结束会有一个换行符,因此要替换掉。

虽然从代码行数上,区别不是太大,但是从方法名称的理解上,startswith和endswith,更容易一些。

4. 匹配多个字符

比如文本内容为:

http://www.sogou.com
this is a url
this is http://www.sogou.com address
ftp://www.sogou.com
#encoding: utf-8
with open("test.txt", "r") as f:
 content = f.readlines()
 for line in content:
 if line.startswith(("http", "ftp")):
 print(line)

只需要传参数为元组,包含要匹配的字串即可。