在网上跟随学习的时候,扒了一段爬虫代码,运行的时候却没有出现网页内容,
代码如下,这是获得网页的代码
# 得到指定一个网址的URL
def askURL(url):
head = { # 模拟浏览器头部信息,向网页服务器发送消息
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" \
"89.0.4389.72 Safari/537.36 Edg/89.0.774.45"}
# 用户代理,表示告诉网页服务器,我们是什么类型机器
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
print(html)
except urllib.error.URLError as UE:
if hasattr(UE, "code"):
print(UE.code)
if hasattr(UE, "reason"):
print(UE.reason)
# return html
这是运行的main内容
def main():
base_url = "https://www.runoob.com/"
# 1.爬取网页
datalist = getdata(base_url)
save_path = ".\\eastmoney_data.xls"
# savedata(save_path=)
askURL("https://www.runoob.com/")
结果是下面的图像
请大家帮忙看看怎么回事,视频里面这段代码之后就出现网页源代码了。。。。
1.导入模块,import urllib.request
2.调用函数,main()。你没有调用main函数,当然不会有结果
import urllib.request,urllib.error
def askURL(url):
head = { # 模拟浏览器头部信息,向网页服务器发送消息
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/" \
"89.0.4389.72 Safari/537.36 Edg/89.0.774.45"}
# 用户代理,表示告诉网页服务器,我们是什么类型机器
request = urllib.request.Request(url, headers=head)
html = ""
try:
response = urllib.request.urlopen(request)
html = response.read().decode("utf-8")
print(html)
except urllib.error.URLError as UE:
if hasattr(UE, "code"):
print(UE.code)
if hasattr(UE, "reason"):
print(UE.reason)
return html
askURL("https://www.douban.com/")
我把这段代码单独提出来是可以运行的,也把网页爬出来了,大佬,你说的调用main是怎么回事呀?我缺了什么东西吗?
你的程序有入口没
代码加上
if __name__ == "__main__":
main()