简体   繁体   English

如果在 beautifulsoup 中找不到元素,如何添加 return none

[英]how to add return none if element not found in beautifulsoup

import requests
from bs4 import BeautifulSoup

respond_timestamp=[]
for i in range(17,18):
    print(i)
    try:
        url='https://www.darooyab.ir/doctor/9/دکتر-شهرام-مظاهری?page='+str(i)
        #print(url)
        response = requests.get(url).content.decode()
    except:
        continue
        
    soup = BeautifulSoup(response,'html.parser') 
    comment= soup.select('div.comment')
    #print( len(comment))
    
    for rt in [i for i in soup.select('div.comment')]:
        try:
            for out in [j.text for j in rt.select('div:nth-child(3) > span:nth-child(1) > label:nth-child(1)')]:
            #print(rt[1])
                pattern=r'دکتر شهرام مظاهری - متخصص قلب و عروق'
                respond_timestamp.append(re.sub(pattern,'',out)) 
        except:
            respond_timestamp.append(None)
            
print(len(respond_timestamp)) 

I want to append respond_timestamp to the list.我想 append respond_timestamp到列表中。 the returned value for respond_timestamp may be empty, then I use try / except and append(None) , But None doesn't add to the list. respond_timestamp的返回值可能为空,然后我使用try / exceptappend(None) ,但None不会添加到列表中。 Because count of the list is important.因为列表的数量很重要。

What should I do?我应该怎么办?

Note Check/print your list, it is not the None that won't be appended, it is your "timestamp" that is missing in the end - Based on your example注意检查/打印您的列表,不是不会附加的 None ,而是最终缺少的“时间戳”-基于您的示例

What happens?怎么了?

  1. Main issue is that re module is not imported (look at your example)主要问题是未导入re模块(查看您的示例)
  2. These not necessary list comprehension make the code very confusing and debugging harder.这些不必要的列表理解使代码非常混乱并且更难调试。 Also it will in case there is no responseComment not start your loop cause it is an empty list and this will make your try successful and won't lead to an exception.此外,如果没有responseComment不会启动您的循环,因为它是一个空列表,这将使您的try成功并且不会导致异常。

How to fix?怎么修?

Import re module to avoid exceptions and change your for loop - Select only one element to check in your try :导入re模块以避免异常并更改您的 for 循环 - Select 只有一个元素要检查您的try

for rt in soup.select('div.comment'):
    try:
        out = rt.select_one('div:nth-child(3) > span:nth-child(1) > label:nth-child(1)').text
        pattern= 'دکتر شهرام مظاهری - متخصص قلب و عروق'
        respond_timestamp.append(re.sub(pattern,'',out)) 
    except Exception as ex:
        print(repr(ex))
        respond_timestamp.append(None) 

Example例子

Note if your goal is to generate dictionaries, do it along the process and not by zipping multiple lists,...请注意,如果您的目标是生成字典,请在整个过程中进行,而不是通过压缩多个列表,...

import requests
from bs4 import BeautifulSoup

data = []
for i in range(17,18):
    try:
        url='https://www.darooyab.ir/doctor/9/دکتر-شهرام-مظاهری?page='+str(i)
        response = requests.get(url).content.decode()
    except:
        continue

    soup = BeautifulSoup(response,'lxml') 

    for c in soup.select('.comment'):
        # pattern=r'دکتر شهرام مظاهری - متخصص قلب و عروق'
        # print(re.sub(pattern,'',c.select_one('div:nth-child(3) > span:nth-child(1) > label:nth-child(1)').text)) 
        data.append({
            'commentDate':c.span.text.split(' ')[1][1:-1],
            'commentText':c.div.text,
            'responseDate':responseDate.text.split(' ')[-1][1:-1] if (responseDate := c.select_one('.responseComment label')) else None,
            'responseText':responseText.text if (responseText := c.select_one('.responseComment .commentText')) else None,
        })

data

Output Output

[{'commentDate': '1398/12/29',
  'commentText': 'سلام من برای الرژیم قرص کیتوتیفن مصرف  میکنم  و برای تنفسم هم خیلی عالیه احساس میکنم ریه هام باز میشه توی دم و باز دم . آیا توی این مدت که این بیماری کرونا اومده استفاده از این دارو رو مشکل ساز است؟\r\n',
  'responseDate': None,
  'responseText': None},
 {'commentDate': 'راهان',
  'commentText': 'با سلام خدمت جناب آقای دکتر. ببخشید من به عل داشتن گواتر قرص لووتیروکسین سدیم 1 مصرف می کنم و تا الان شش کیلو وزن کم کردم . ممکنه راهنماییبفرمایید چکار کنم تا کاهش وزنم متوقف بشه. سپاسگزارم ',
  'responseDate': '1399/2/25',
  'responseText': 'سلام مربوط به قلب نمی شود'},
 {'commentDate': '1398/12/28',
  'commentText': 'سلام . من دیروز به دلیل درد معده و اسهال بیش از حد به پزشک مراجعه کردم . برای من سیپروفلوکساسین و دیفنوکسیلات تجویز کردن . مصرف که میکنم اسید معدم میاد تو دهانم . میخواستم بدونم مشکل از دارو هست یا بنده م',
  'responseDate': '1399/2/25',
  'responseText': 'سلام مربوط به قلب نمی شود'},
...]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM