【问题标题】:python beautifulsoup and writing to CSV (multiple URLs)python beautifulsoup 并写入 CSV(多个 URL)
【发布时间】:2018-06-10 01:32:05
【问题描述】:

这是我目前所拥有的:

import csv, re
from bs4 import BeautifulSoup as soup
import requests
flag = False
with open('filename.csv', 'w') as f:
  write = csv.writer(f)
  for i in range(38050, 38050): ##this is so I can test run with one page 
    s = soup(requests.get('https://howlongtobeat.com/game.php?id={i}').text, 'html.parser')
    if not flag: #write header to file once
      write.writerow(['Name', 'Length']+[re.sub('[:\n]+', '', i.find('strong').text) for i in s.find_all('div', {'class':'profile_info'})])
      flag = True
  ## this is for if there is no page or an error  
content = s.find('div', {"class":'profile_header shadow_text'})
if content: 
  name = s.find('div', {"class":'profile_header shadow_text'}).text
  length = [[i.find('h5').text, i.find("div").text] for i in s.find_all('li', {'class':'time_100'})]
  stats = [re.sub('\n+[\w\s]+:\n+', '', i.text) for i in s.find_all('div', {'class':'profile_info'})]

这不是写 csv 也不知道为什么(我只是个初学者)

我正在尝试创建一个循环来检查这些元素是否存在,如果存在则将它们写入“hltb.csv”

我该怎么做?

【问题讨论】:

    标签: python loops csv web-scraping beautifulsoup


    【解决方案1】:

    您正在迭代一个空范围。

    for i in range(38050, 38050):
    

    这个范围的大小是0。尝试将最大值增加1。

    for i in range(38050, 38051):
    

    【讨论】:

      【解决方案2】:

      您可能需要增加 for 循环中的值。

      page = 38050
      for i in range(0,page):
          page += 1
      

      此脚本将永远运行。您需要添加某种 HTTP STATUS CODE 404 处理程序,以防您找不到任何处理程序,以便脚本结束。我认为您所做的做法很糟糕

      【讨论】:

      • TypeError: 'int' object is not iterable
      • @DeliriousLettuce 更新了我的答案,抱歉我的语法不好。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-04-15
      • 2020-01-12
      • 2017-04-27
      • 2017-06-18
      • 2018-04-02
      • 2014-10-06
      • 1970-01-01
      相关资源
      最近更新 更多