import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.Text
except:
return"产生异常"
if _name_=="_main_":
url="http://www.baidu.com"
print(getHTMLText(url))
上面是代码程序,当运行时出现NameError: name '_name_' is not defined,其实_name_=="_main_"该条语句都有问题,当把语句改为__name__=="__main__",总结就是该条语句原来定义的短线为长线。当继续运行代码:
Import requests
def getHTMLText(url):
try:
r=requests.get(url,timeout=30)
r.raise_for_status()
r.encoding=r.apparent_encoding
return r.Text
except:
return"产生异常"
if _name_=="_main_":
url="http://www.baidu.com"
print(getHTMLText(url))
>>>产生异常
输出为“产生异常”,说明爬取不成功,通过文本代码把r.Text改为r.text时,得到如下结果:
<!--STATUS OK--><html> <head><meta http-equiv=content-type content=text/html;charset=utf-8><meta http-equiv=X-UA-Compatible content=IE=Edge><meta content=always name=referrer><link rel=stylesheet type=text/css href=http://s1.bdstatic.com/r/www/cache/bdorz/baidu.min.css><title>.......