【问题标题】:how can i check parameter in while loop for each item in array?如何检查数组中每个项目的while循环中的参数?
【发布时间】:2019-11-24 01:56:24
【问题描述】:

我正在尝试从旧网站获取标题。

在某些情况下我遇到的问题 - null 值。 因此,我尝试做一个while循环并更改URL。

我的While 循环在正确的位置吗?

过程是这样的:

  1. 打开文件
  2. 获取网址
  3. 查看网址
  4. 获取标题
  5. 打印标题
  6. 而标题 = null):
  7. 替换部分url,再次检查url
from urllib.request import urlopen
from bs4 import BeautifulSoup
from openpyxl import Workbook
import os
import xlrd
import lxml

# set file location
os.chdir("/excel_files")

# set the name of the file
file_name = "old.xlsx"

# open workbook
workbook = xlrd.open_workbook(file_name)

# set existing worksheet
sheet = workbook.sheet_by_index(0)


temp_list = [20131022212405,20090127003537,2009012702352,]

for i in range(sheet.nrows):
    try:
        u = sheet.cell_value(i,1)
    html = urlopen(u)
    bsObj = BeautifulSoup(html.read(), features='lxml')
    # get title
    title = str(bsObj.title)
    print('row no. ',i, 'title is :' , title)
except:
    title = 'null'
while (title == 'null'):
    try:
        u = u.replace(temp_list[i], temp_list[i + 1])
        html = urlopen(u)
        bsObj = BeautifulSoup(html.read(), features='lxml')
        title = str(bsObj.title)
    except:
        print('title is :',title)

我一直得到null - 而不是只得到实际上是null 的行。

【问题讨论】:

    标签: python python-3.x arraylist while-loop beautifulsoup


    【解决方案1】:

    看起来您在第一个 for 循环 (for i in range(sheet.nrows):) 中的 try/except 缩进是错误的,tryexcept 应该在同一级别。

    【讨论】:

    • 很抱歉,我不能将 try/except 与 for 放在同一级别 - 我遇到错误
    猜你喜欢
    • 2020-04-13
    • 1970-01-01
    • 2016-01-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-22
    • 1970-01-01
    相关资源
    最近更新 更多