Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/287.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 刮取跳过部分页面url,不会将所有值写入CSV_Python_Python 2.7_Beautifulsoup - Fatal编程技术网

Python 刮取跳过部分页面url,不会将所有值写入CSV

Python 刮取跳过部分页面url,不会将所有值写入CSV,python,python-2.7,beautifulsoup,Python,Python 2.7,Beautifulsoup,我是Python新手。我昨天才开始。我想浏览一个网站,收集字典里的数据。 所有导入都添加在python脚本的开头 title_and_urls = {} #dictionary totalNumberOfPages = 12 for x in range(1,int(totalNumberOfPages)+1): url_pages = 'https://abd.com/api?&page=' +str(x)+'&year=2017' resp = request

我是Python新手。我昨天才开始。我想浏览一个网站,收集字典里的数据。 所有导入都添加在python脚本的开头

title_and_urls = {} #dictionary
totalNumberOfPages = 12
for x in range(1,int(totalNumberOfPages)+1):
    url_pages = 'https://abd.com/api?&page=' +str(x)+'&year=2017'
    resp = requests.get(url_pages, timeout=60)
    soup = BeautifulSoup(resp.text, 'lxml')
    for div in soup.find_all('div', {"class": "block2"}):
        a = div.find('a')
        h3 = a.find('h3')
        print(h3,url_pages) #prints correct
        title_and_urls[h3.text] = base_enthu_url+a.attrs['href']

print(title_and_urls)


with open('dict.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in title_and_urls.items():
       writer.writerow([key, value])
这里有几个问题 1.我总共有12页,但它跳过了第7页和第8页 2.打印行printh3、url_页面打印了60个项目,而csv文件只有36个项目

我感谢所有的帮助和解释。请建议最佳做法

使用试用功能

**title_and_urls = {} #dictionary
totalNumberOfPages = 12
for x in range(1,int(totalNumberOfPages)+1):
    try:
        url_pages = 'https://abd.com/api?&page=' +str(x)+'&year=2017'
        resp = requests.get(url_pages, timeout=60)
        soup = BeautifulSoup(resp.text, 'lxml')
        for div in soup.find_all('div', {"class": "block2"}):
            a = div.find('a')
            h3 = a.find('h3')
            print(h3,url_pages) #prints correct
            title_and_urls[h3.text] = base_enthu_url+a.attrs['href']
    except:
        pass


with open('dict.csv', 'wb') as csv_file:
    writer = csv.writer(csv_file)
    for key, value in title_and_urls.items():
       writer.writerow([key, value])**

你能分享真实的网址吗?可能由于某种原因,这些特定页面的查询发生了更改。另外:您需要使用BeautifulSoup吗?使用Scrapy.@a.Lorefice,我有了更好的抓取几页的体验。谢谢您的评论。这些特定页面没有变化。我已经手动报废了它,它可以工作了。所以我在一天内就学会了这一点,我在网上找到的教程中并没有遇到零碎的东西。还有,为什么字典在打印60个条目时只包含36个条目?没有变化,我仍然有相同的问题更新了我的代码,请检查打印的行数和CSV中的行数。请解释您修改的代码?我做错了什么?您已经编写了两次打印命令,这是再次打印最后一行。printtitle_和_Url共12页,共72个结果。但是,每次我运行程序时,它都会返回随机数目的结果。有时是36,有时是41。程序不一致。