【发布时间】: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