龙心 发表于 2020-11-24 22:56:30

爬虫问题求解

为什么下面代码运行了之后也没有报错也没有爬到IP地址
同问小甲鱼《零基础入门学python》里面爬虫那部分正则表达式相关的所有代码都有这个问题,不知道怎么改。。。

import urllib.request
import re

def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')
    page = urllib.request.urlopen(req)
    html = page.read().decode('utf-8')
   
    return html

def get_img(html):
    p = r'(?:(?:?\d?\d|2\d|25)\.){3}(?:?\d?\d|2\d|25)'
    iplist = re.findall(p,html)

    for each in iplist:
      print(each)


if __name__ == '__main__':
    url = "https://cn.proxy.com/"
    get_img(open_url(url))



均昊山 发表于 2020-11-24 23:10:32

先 打印有没有 获取到网页内容,然后打印调试正则有没有问题

龙心 发表于 2020-11-30 21:51:56

假面的假面 发表于 2020-11-24 23:37
网站都打不开你还打算爬虫?

换网址url也没用啊,什么反应都没有

龙心 发表于 2020-11-30 22:05:03

均昊山 发表于 2020-11-24 23:10
先 打印有没有 获取到网页内容,然后打印调试正则有没有问题

下面代码运行了还是啥都没出来。。。。


import urllib.request
import re


def open_url(url):
    req = urllib.request.Request(url)
    print(f"req ={req}")
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')
    print(f"req ={req}")
    page = urllib.request.urlopen(req)
    print(f"page ={page}")
    html = page.read().decode('utf-8')
    print(f"html ={html}")
   
   
    return html

def get_img(html):
    p = r'(?:(?:?\d?\d|2\d|25)\.){3}(?:?\d?\d|2\d|25)'
    iplist = re.findall(p,html)

    for each in iplist:
      print(each)


if __name__ == '__main__':
    url = "https://www.bilibili.com/"
    html = open_url(url)
    print(f"html = {html}")
    pic = get_img(html)
    print(f"pic = {pic}")

龙心 发表于 2020-11-30 22:30:00

假面的假面 发表于 2020-11-24 23:37
网站都打不开你还打算爬虫?

抱歉,换个网址可以用了,应该是网址打不开,然后前面可能我换的网址里面爬不到IP地址,所以程序没有任何输出。
还有安装的python有点问题,没有一个dell文件,导致运行过程中出错了,用powershell运行没反应,用cmd运行才提示安装的python里面少了一个dell问文件。。。
重新安装python+更改url之后可以成功爬到IP地址了!!!

import urllib.request
import re


def open_url(url):
    req = urllib.request.Request(url)
    req.add_header('User-Agent','Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/65.0.3325.181 Safari/537.36')
    page = urllib.request.urlopen(req)
    html = page.read().decode('utf-8')
   
    return html

def get_img(html):
    p = r'(?:(?:?\d?\d|2\d|25)\.){3}(?:?\d?\d|2\d|25)'
    iplist = re.findall(p,html)

    for each in iplist:
      print(each)


if __name__ == '__main__':
    url = "https://www.kuaidaili.com/free/"
    html = open_url(url)
    # print(html)
    pic = get_img(html)
    # print(pic)
页: [1]
查看完整版本: 爬虫问题求解