运行结果就是个[],这是怎么回事


def get_mobile(phone):
    url='https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile'
    import requests
    from lxml import etree
    headers={'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203'}

    resp=requests.get(url,headers=headers)
    
    resp.encoding='utf-8'
    #解析数据
    e=etree.HTML(resp.text)
    #编写xpath提取数据
    data=e.xpath('//tr/td[2]/span/text()')
    #解析响应
    print(data)

get_mobile(13000000000)

(1)确认网站返回了数据了么
(2)data=e.xpath('//tr/td[2]/span/text()') 确认这个 xpath 对么

【以下回答由 GPT 生成】

运行结果只是一个空列表[]的原因是因为在请求的URL中,phone={phone}没有被正确地替换为实际的手机号。作为一个String,phone={phone}并没有数值,而只是一个模板。

为了解决这个问题,你可以使用Python的字符串格式化功能,将{phone}替换为实际的手机号。你可以使用字符串的format()方法来实现这一点。在你的代码中,将URL字符串 url = 'https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile' 改为 url = 'https://www.ip138.com/mobile.asp?mobile={}&action=mobile'.format(phone)。这样,URL中的{}会被实际的手机号phone所替换。

下面是修改后的代码:

def get_mobile(phone):
    url = 'https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile'
    import requests
    from lxml import etree
    headers = {'User-Agent':'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/115.0.0.0 Safari/537.36 Edg/115.0.1901.203'}

    resp = requests.get(url.format(phone), headers=headers)  # 将{phone}替换为实际的手机号

    resp.encoding='utf-8'
    #解析数据
    e = etree.HTML(resp.text)
    #编写xpath提取数据
    data = e.xpath('//tr/td[2]/span/text()')
    #解析响应
    print(data)

get_mobile(13000000000)

修改后的代码中,url = 'https://www.ip138.com/mobile.asp?mobile={phone}&action=mobile'这一行中的{phone}已经被format(phone)替换掉了。运行代码后,你将得到提取到的数据。



【相关推荐】



如果你已经解决了该问题, 非常希望你能够分享一下解决方案, 写成博客, 将相关链接放在评论区, 以帮助更多的人 ^-^

确定返回数据了吗