Python网页中的重复项

2024-04-26 04:36:54 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图建立一个网络爬虫,以获得特定的价值观,从一个网页。这些值可能会被更新,我不想在输出中获取以前的值。你知道吗

下面是我的问题的一个简化示例:

html_example=''' 
<value> this is the updated value 
Keyword "previous" that tell me I don't want the next value. 
<valueIdontwant> this is the previous value
<value> this value has not been updated
<value> this is the updated value 
Keyword "previous" that tell me I don't want the next value. 
<valueIdontwant> this is the previous value
<value> this value has not been updated 
'''

我正在使用的代码(基于教授的Dave MOOC)

def get_values(content):
    values=[]
    while True:
        start_value=content.find('<')
        end_value=content.find('>', start_value+1)
        value=content[start_value+1:end_value]
        if value:
          values.append(value)
          content=content[end_value:]
        else:
            break
    return values

get_values(html_example)

我得到的输出:

['value', 'valueIdontwant', 'value', 'value', 'valueIdontwant', 'value']

我想要得到的输出:

['value', 'value', 'value', 'value']

跟踪我想省略的值的唯一方法是关键字“previous”,而不是它自己的值(在我的情况下,“for value in values”类代码将不起作用)。你知道吗

我是一个相当新的编程,我真的很不擅长,我尝试了不同的“如果”语句,但没有成功。如果您对如何解决这个问题有任何想法,请提前感谢!你知道吗


Tags: thethatisvalueexamplehtmlcontentthis
1条回答
网友
1楼 · 发布于 2024-04-26 04:36:54

代码很复杂,不太像python,但如果您希望对列表进行索引访问,请查找enumerate()。你知道吗

def get_values_ignore_current_line(content, keyword):
   content = '\n'.join([x for x in content.splitlines() if keyword not in x]) 
   tags = re.findall('<.*?>', content)
   return tags

def get_values_ignore_next_line(content, keyword):
    lines = content.splitlines()
    new_content = [lines[0]]
    for i, line in enumerate(lines):
        if (keyword not in line) or (re.match('<.*?>', line) is not None):
            if i < len(lines) - 1:
                new_content.append(lines[i+1])
    new_content = '\n'.join(new_content)
    return re.findall('<.*?>', new_content)

相关问题 更多 >