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. 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. Because count of the list is important.
What should I do?
CodePudding user response:
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
What happens?
- Main issue is that
remodule is not imported (look at your example) - These not necessary list comprehension make the code very confusing and debugging harder. Also it will in case there is no
responseCommentnot start your loop cause it is an empty list and this will make yourtrysuccessful and won't lead to an exception.
How to fix?
Import re module to avoid exceptions and change your for loop - Select only one element to check in your 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
[{'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': 'سلام مربوط به قلب نمی شود'},
...]
