我正在检索过去某个日期发布的一些文章。 以下是我的代码的一部分:
def get_articles(dom, date):
soup = BeautifulSoup(dom, 'html.parser')
articles = []
divs = soup.find_all('div', "r-ent")
for d in divs:
print("A")
print(d.find('div', 'date').string, date)
if d.find('div', 'date').string == date: #Where the problem is.
print("YYYYYYYYYY")
...
return articles
import time
page = get_web_page('https://www.ptt.cc/bbs/joke/index.html')
if page:
date = time.strftime("%m/%d").lstrip('0') # date is string
current_articles = get_articles(page, date)
for post in current_articles:
print(post)
#A
#2/01 2/01
#A
#2/01 2/01
#A
#2/01 2/01
#A
#2/01 2/01
#A
#2/01 2/01
#A
#2/01 2/01
#A
#2/01 2/01
#A
#11/04 2/01
理想情况下,YYYYYYYYYY
应该在
时打印
d.find('div', 'date').string == date
为什么代码执行不理想,我如何对其进行编辑?
答案 0 :(得分:1)
根据评论,我使用repr()检查区别在哪里。
repr(d.find('div', 'date').string.lstrip()) == repr(date)
# ' 2/01' '2/01'
所以我需要删除空白
d.find('div', 'date').string.lstrip() == date
# '2/01' '2/01'
然后条件为真。