此代码仅在python2.7上运行?

时间:2017-02-21 01:25:39

标签: python python-3.x web-scraping beautifulsoup code-formatting

编辑我刚刚弄清楚map()函数是什么导致它无法正常运行我不知道为什么但至少现在正在运行感谢所有的帮助:)

我刚刚通过pycharm将我的代码更新为pep8代码样式指南,但是现在它只在python2上运行,当我运行python3时我得到了这个错误。

Traceback (most recent call last):
  File "main.py", line 28, in <module>
    soup.find_all("td", {"class": "location"})[1:],soup.find_all("td", {"class": "date-time"})[1:]):
TypeError: 'NoneType' object is not callable

跟踪号码也不是我的,我只是在互联网上找到它。     导入系统     导入请求     来自bs4 import BeautifulSoup

s = requests.Session()
s.headers['User-Agent'] = 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/34.0.1847.131 Safari/537.36 '
#if len(sys.argv) == 2:
#    trackingNumber = sys.argv[1]
#else:
#    print("Enter a tracking number to track a number.")
#    sys.exit()
r = s.get("https://tools.usps.com/go/TrackConfirmAction.action?tRef=fullpage&tLc=1&text28777=&tLabels=CX263292019US")
soup = BeautifulSoup(r.text, "lxml")



# Variable declaration.
current_status = soup.find(class_="detail-summary", )
some = soup.find_all("div", {"id": "tracking-results"})

for tag in some:
    divTags = tag.find_all("li")
    for tag in divTags:
        testrip = tag.encode("utf-8").strip()  # Remove all the white space off the text from bs4.
        if testrip == "The Postal Service could not locate the tracking information for your request." \
                      " Please verify your tracking number and try again later.":
            break

print(
    "----------------------------------------------------------------------------------------------------------------")

print(current_status.get_text().strip())
for Status, Location, Time in map(None, soup.find_all("span", {"class": "info-text"}),
                                  soup.find_all("td", {"class": "location"})[1:],
                                  soup.find_all("td", {"class": "date-time"})[1:]):

    print(
        "----------------------------------------------------------------------------------------------------------------")
    try:
        print(Status.get_text().strip())
        print(Location.get_text().strip())
        print(" ".join(Time.get_text().split()))
    except Exception:
        pass
print(
    "----------------------------------------------------------------------------------------------------------------")

1 个答案:

答案 0 :(得分:0)

快速但短期的可持续解决方案:

  • 添加from __future__ import print_function(现在使用Python3语法)
  • 检查两个Pythons下的导入是否有效? (在大多数情况下,他们默认使用Python,但谁知道你的发行版是什么)
  • 如果上述任何内容无效,则发布堆栈跟踪

更长期的解决方案:Pycharm中的turn on Python 3 syntax checks

  

设置 - &gt;编辑 - &gt;检查 - &gt; Python - &gt;代码兼容性检查