python - 无法保留特定项目并忽略其余项目

标签 python python-3.x if-statement web-scraping

我已经用 Python 编写了一些代码来从三个不同的站点抓取特定项目。对于每个站点,元素中的项目是不同的。所以,我必须创建三个不同的选择器来捕捉它们。我的脚本将在一个站点中寻找一个项目,如果在第一个站点中找不到,它会继续寻找另一个项目,依此类推。我想要实现的是,如果爬虫在它的第一次搜索中找到该项目,这意味着在第一个链接中,那么它将忽略其余的链接,依此类推。然而,我面临的问题是,如果爬虫在链接二中找到了它想要的项目,然后在它转到第三个链接时又没有找到任何东西,它就不会打印任何东西。我该如何修复我的脚本,以便它在任何链接中找到任何特定项目后立即停止搜索。

我的脚本的外观更像下面的脚本:

import requests
from lxml.html import fromstring

list_urls = ['url1','url2','url3']

for link in list_urls:
    res = requests.get(link).text
    root = fromstring(res)
    try:
        item = root.cssselect(some_selector)[0].text
    except:
        item =""
    try:
        item = root.cssselect(another_selector)[0].text
    except:
        item =""
    try:
        item = root.cssselect(some_other_selector)[0].text
    except:
        item =""
    print(item)

最佳答案

首先,如果您在第一个搜索中成功,则必须阻止您的语句进入下一个搜索。你可以尝试这样的事情:

for link in list_urls:
    res = requests.get(link).text
    root = fromstring(res)
    try:
        item = root.cssselect(some_selector)[0].text
    except:
        item =""
        try:
            item = root.cssselect(another_selector)[0].text
        except:
            item =""
            try:
                item = root.cssselect(some_other_selector)[0].text
            except:
                item =""
    print(item)

或者更好:

for link in list_urls:
    res = requests.get(link).text
    root = fromstring(res)
    try:
        item = root.cssselect(some_selector)[0].text
        print(item) 
        continue
    except:
        item =""
    try:
        item = root.cssselect(another_selector)[0].text
        print(item) 
        continue
    except:
        item =""
    try:
        item = root.cssselect(some_other_selector)[0].text
        print(item) 
        continue
    except:
        item =""

关于python - 无法保留特定项目并忽略其余项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46912995/

相关文章:

python - 为什么 Python threading.Condition() notify() 需要锁?

if-statement - Fortran IF 循环

python - 根据共性对字符串数组进行分类

Python JSON序列化排除某些字段

python - numpy数组中小于(<)运算符的作用是什么?

python - Unresolved reference : 'django' error in PyCharm

python - 我不明白这个(功能?)是如何工作的

python - 如何在第二代应用程序引擎上下载 Spacy 模型?

c - 如何修复 "Debug Error!, Stack around the variable ' x' 已损坏”?

对 char 和 char * 感到困惑,并在单词中扫描