复杂的python3 csv刮刀

时间:2018-05-22 06:51:43

标签: python-3.x csv scraper

我从一行中提取数据时,下面的代码工作得很好,在我的情况下 row [0] 。我想知道如何调整它以从多行中提取数据?

此外,我希望能够指定用于特定列的 divTag类(请参阅下面的代码)。

对于行[1,2] 的使用:

divTag = soup.find("div", {"class": "productsPicture"})

行[4,5] 使用:

divTag = soup.find("div", {"class": "product_content"})

如果那对你们有意义的话。

from bs4 import BeautifulSoup
import requests
import csv

with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results:
reader = csv.reader(csvFile, delimiter=';')
writer = csv.writer(results)

for row in reader:
    # get the url
    url = row[0]
    print(url)

    # fetch content from server

    try:
        html = requests.get(url).content
    except requests.exceptions.ConnectionError as e:
        writer.writerow([url, '', 'bad url'])
        continue

    # soup fetched content
    soup = BeautifulSoup(html, 'html.parser')

    divTag = soup.find("div", {"class": "productsPicture"})

    if divTag:
        # Return all 'a' tags that contain an href
        for a in divTag.find_all("a", href=True):
            url_sub = a['href']

            # Test that link is valid
            try:
                r = requests.get(url_sub)
                writer.writerow([url, url_sub, 'ok'])
            except requests.exceptions.ConnectionError as e:
                writer.writerow([url, url_sub, 'bad link'])
    else:
        writer.writerow([url, '', 'no results'])

urls.csv示例:

https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E705Y-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E703Y-0193;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E702Y-4589;
https://www.tennis-point.com/index.php?stoken=737F2976&lang=1&cl=search&searchparam=E706Y-9093;

要搜索的示例类:

classes to search for per column

1 个答案:

答案 0 :(得分:1)

要添加每列查找参数,您可以创建一个字典,将索引号映射到所需的查找参数,如下所示:

from bs4 import BeautifulSoup
import requests
import csv

class_1 = {"class": "productsPicture"}
class_2 = {"class": "product_content"}
class_3 = {"class": "id-fix"}

# map a column number to the required find parameters
class_to_find = {
    0 : class_3,    # Not defined in question
    1 : class_1,    
    2 : class_1,
    3 : class_3,    # Not defined in question
    4 : class_2, 
    5 : class_2}

with open('urls.csv', 'r') as csvFile, open('results.csv', 'w', newline='') as results:
    reader = csv.reader(csvFile)
    writer = csv.writer(results)

    for row in reader:
        # get the url

        output_row = []

        for index, url in enumerate(row):
            url = url.strip()

            # Skip any empty URLs
            if len(url):
                #print('col: {}\nurl: {}\nclass: {}\n\n'.format(index, url, class_to_find[index]))

                # fetch content from server

                try:
                    html = requests.get(url).content
                except requests.exceptions.ConnectionError as e:
                    output_row.extend([url, '', 'bad url'])
                    continue
                except requests.exceptions.MissingSchema as e:
                    output_row.extend([url, '', 'missing http...'])
                    continue

                # soup fetched content
                soup = BeautifulSoup(html, 'html.parser')


                divTag = soup.find("div", class_to_find[index])

                if divTag:
                    # Return all 'a' tags that contain an href
                    for a in divTag.find_all("a", href=True):
                        url_sub = a['href']

                        # Test that link is valid
                        try:
                            r = requests.get(url_sub)
                            output_row.extend([url, url_sub, 'ok'])
                        except requests.exceptions.ConnectionError as e:
                            output_row.extend([url, url_sub, 'bad link'])
                else:
                    output_row.extend([url, '', 'no results'])      

        writer.writerow(output_row)

enumerate()函数用于返回迭代列表的计数器。因此,第一个网址index0,下一个网址为1。然后,可以将其与class_to_find字典一起使用,以获取要搜索的必需参数。

每个URL都会创建3列,url,sub-url(如果成功)和结果。如果不需要,可以删除它们。