【问题标题】:How to get around "MissingSchema" error in Python?如何解决 Python 中的“MissingSchema”错误?
【发布时间】:2017-12-17 00:40:24
【问题描述】:

运行我的脚本后,我注意到我的“parse_doc”函数在找到任何 url None 时都会抛出错误。结果是,我的“process_doc”函数应该产生 25 个链接,但它只产生 19 个,因为很少有页面没有任何链接可以指向另一个页面。但是,当我的第二个函数接收到具有 None 值的链接时,它会产生指示“MissingSchema”的错误。如何解决这个问题,以便当它找到任何具有 None 值的链接时,它会去另一个链接。这是我的脚本的部分内容,可以让您了解我的意思:

def process_doc(medium_link):

    page = requests.get(medium_link).text
    tree = html.fromstring(page)
    try:
        name = tree.xpath('//span[@id="titletextonly"]/text()')[0]
    except IndexError:
        name = ""
    try:
        link = base + tree.xpath('//section[@id="postingbody"]//a[@class="showcontact"]/@href')[0]
    except IndexError:
        link = ""

    parse_doc(name, link)   "All links get to this function whereas some links are with None value

def parse_doc(title, target_link):
    page = requests.get(target_link).text   # Error thrown here when it finds any link with None value

    tel = re.findall(r'\d{10}', page)[0] if re.findall(r'\d{10}', page) else ""
    print(title, tel)

我得到的错误:

raise MissingSchema(error)
requests.exceptions.MissingSchema: Invalid URL '': No schema supplied. Perhaps you meant http://?

顺便说一句,在我的第一个函数中,有一个名为“base”的变量,用于与生成的结果连接以建立完整的链接。

【问题讨论】:

    标签: python python-3.x error-handling web-scraping python-requests


    【解决方案1】:

    如果您想避免target_link == None 出现的情况,请尝试

    def parse_doc(title, target_link):
        if target_link:
            page = requests.get(target_link).text            
            tel = re.findall(r'\d{10}', page)[0] if re.findall(r'\d{10}', page) else ""
            print(tel)
        print(title)
    

    这应该只允许您处理 非空 链接,否则什么也不做

    【讨论】:

      【解决方案2】:

      首先确保您的架构(即 url)是正确的。有时您只是缺少一个字符或在https:// 中有一个太多字符。 如果您必须引发异常,尽管您可以这样做:

      import requests
      from requests.exceptions import MissingSchema
      
      ...
      
      try:
          res = requests.get(linkUrl)
          print(res) 
      except MissingSchema:
          print('URL is not complete')
      
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-10-08
        • 1970-01-01
        • 2023-04-02
        • 2020-10-31
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多