小编Sam*_*gan的帖子

Python f 字符串格式不适用于内联 strftime

我遇到了一个我试图理解的奇怪错误。进行一些常规代码清理并将所有字符串格式转换为 f 字符串。这是在 Python 3.6.6 上

此代码不起作用:

from datetime import date
print(f'Updated {date.today().strftime('%m/%d/%Y')}')

  File "<stdin>", line 1
    print(f'Updated {date.today().strftime('%m/%d/%Y')}')
                                               ^
SyntaxError: invalid syntax
Run Code Online (Sandbox Code Playgroud)

但是,这(功能相同)确实有效:

from datetime import date
d = date.today().strftime('%m/%d/%Y')
print(f'Updated {d}')

Updated 11/12/2018
Run Code Online (Sandbox Code Playgroud)

我觉得我可能遗漏了一些明显的东西,并且第二次迭代很好,但我想了解这里发生了什么。

python string-formatting python-3.x f-string

8
推荐指数
2
解决办法
7357
查看次数

亚马逊使用 bs4、请求阻止了 Python 3 抓取

几天前,当我运行它时,此代码工作正常:

from bs4 import BeautifulSoup
import datetime
import requests

def getWeekMostRead(date):
    nonfiction_page = requests.get("https://www.amazon.com/charts/"+date.isoformat()+"/mostread/nonfiction")
    content = "amazon"+date.isoformat()+"_nonfiction.html"
    with open(content, "w", encoding="utf-8") as nf_file:
        print(nonfiction_page.content, file=nf_file)

    mostRead_nonfiction = BeautifulSoup(nonfiction_page.content, features="html.parser")

    nonfiction = mostRead_nonfiction.find_all("div", class_="kc-horizontal-rank-card")

    mostread = []
    for books in nonfiction:
        if books.find(class_="kc-rank-card-publisher") is None:
            mostread.append((
                books.find(class_="kc-rank-card-title").string.strip(),
                books.find(class_="kc-rank-card-author").string.strip(),
                "",
                books.find(class_="numeric-star-data").small.string.strip()
            ))
        else:
            mostread.append((
                books.find(class_="kc-rank-card-title").string.strip(),
                books.find(class_="kc-rank-card-author").string.strip(),
                books.find(class_="kc-rank-card-publisher").string.strip(),
                books.find(class_="numeric-star-data").small.string.strip()
            ))
    return mostread

mostread = []
date = datetime.date(2020,1,1)
while date >= datetime.date(2015,1,1):
    print("Scraped data from "+date.isoformat())
    mostread.extend(getWeekMostRead(date))
    date -= datetime.timedelta(7)
print("Currently saving scraped …
Run Code Online (Sandbox Code Playgroud)

python beautifulsoup web-scraping python-3.x

1
推荐指数
1
解决办法
1277
查看次数