在解析时遍历列表

在解析时遍历列表

问题描述:

我正在尝试下载此锻炼的工作表,所有锻炼都在不同的日子进行拆分。所有需要做的是在链接的末尾添加一个新号码。这是我的代码。在解析时遍历列表

import urllib 
 
import urllib.request 
 
from bs4 import BeautifulSoup 
 
import re 
 
import os 
 
theurl = "http://www.muscleandfitness.com/workouts/workout-routines/gain-10-pounds-muscle-4-weeks-1?day=" 
 
urls = [] 
 
count = 1 
 
while count <29: 
 
    urls.append(theurl + str(count)) 
 
    count +=1 
 
print(urls) 
 
for url in urls: 
 
    thepage = urllib 
 
    thepage = urllib.request.urlopen(urls) 
 
    soup = BeautifulSoup(thepage,"html.parser") 
 
    init_data = open('/Users/paribaker/Desktop/scrapping/workout/4weekdata.txt', 'a') 
 
    workout = [] 
 

 
    for data_all in soup.findAll('div',{'class':"b-workout-program-day-exercises"}): 
 
     try: 
 
      for item in data_all.findAll('div',{'class':"b-workout-part--item"}): 
 
       for desc in item.findAll('div', {'class':"b-workout-part--description"}): 
 
        workout.append(desc.find('h4',{'class':"b-workout-part--exercise-count"}).text.strip("\n") +",\t") 
 
        workout.append(desc.find('strong',{'class':"b-workout-part--promo-title"}).text +",\t") 
 
        workout.append(desc.find('span',{'class':"b-workout-part--equipment"}).text +",\t") 
 
       for instr in item.findAll('div', {'class':"b-workout-part--instructions"}): 
 
        workout.append(instr.find('div',{'class':"b-workout-part--instructions--item workouts-sets"}).text.strip("\n") +",\t") 
 
        workout.append(instr.find('div',{'class':"b-workout-part--instructions--item workouts-reps"}).text.strip("\n") +",\t") 
 
        workout.append(instr.find('div',{'class':"b-workout-part--instructions--item workouts-rest"}).text.strip("\n")) 
 
        workout.append("\n*3") 
 
     except AttributeError: 
 
      pass 
 

 
init_data.write("".join(map(lambda x:str(x), workout))) 
 
init_data.close

的问题是,服务器超时,我假设它不是通过列表迭代正常或添加我不需要文字和崩溃的服务器解析器。 我也试着编写另一个脚本来抓取所有链接并将它们放在文本文档中,然后重新打开此脚本中的文本并遍历文本,但这同样给了我同样的错误。你怎么看?

有一个错字这里:

thepage = urllib.request.urlopen(urls) 

你可能想:

thepage = urllib.request.urlopen(url) 

否则你试图打开网址,而不是单一的一个数组。

+0

所以我有意使用URLs-urls是我在第7行使用theurl + count创建的新列表。 –

+0

哦!是的,我明白了,让我试试看。 –

+0

完美的工作非常感谢额外的眼睛! –