Python Webscrape HTML в CSV файл для цикла - PullRequest
0 голосов
/ 01 января 2019

Я довольно новичок в Python и мне тяжело с моим циклом For, чтобы извлечь все веб-ссылки на определенном сайте.Вот мой код:

import requests
import csv
from bs4 import BeautifulSoup
j= [["Population and Housing Unit Estimates"]] # Title
k= [["Web Links"]] # Column Headings
example_listing='https://www.census.gov/programs-surveys/popest.html' #Source
r=requests.get(example_listing) #Grab page source html
html_page=r.text
soup=BeautifulSoup(html_page,'html.parser') #Build Beautiful Soup object to help parse the html
with open('HTMLList.csv','w',newline="") as f: #Choose what you want to grab
    writer=csv.writer(f,delimiter=' ',lineterminator='\r')
    writer.writerows(j)
    writer.writerows(k)
    for link in soup.find_all('a'):
        f.append(link.get('href'))
        if not f:
            ""
        else:
            writer.writerow(f)
f.close()

Любая помощь очень ценится.Я действительно не знаю, куда идти отсюда.Спасибо!

Ответы [ 2 ]

0 голосов
/ 01 января 2019
import requests
import csv
from bs4 import BeautifulSoup
j= ["Population and Housing Unit Estimates"] # Title
k= ["Web Links"] # Column Headings
example_listing='https://www.census.gov/programs-surveys/popest.html' #Source
r=requests.get(example_listing) #Grab page source html
html_page=r.text
soup=BeautifulSoup(html_page,'html.parser') #Build Beautiful Soup object to help parse the html
with open('HTMLList.csv','w',newline="") as f: #Choose what you want to grab
    writer=csv.writer(f,delimiter=' ',lineterminator='\r')
    writer.writerow(j)
    writer.writerow(k)
    for link in soup.find_all('a'):
        if link.get('href') is not None:
            writer.writerow([link.get('href')])

HTMLList.csv

"Population and Housing Unit Estimates"
"Web Links"
https://www.census.gov/en.html
https://www.census.gov/topics/population/age-and-sex.html
https://www.census.gov/topics/business-economy.html
https://www.census.gov/topics/education.html
https://www.census.gov/topics/preparedness.html
https://www.census.gov/topics/employment.html
https://www.census.gov/topics/families.html
https://www.census.gov/topics/population/migration.html
https://www.census.gov/geography.html
https://www.census.gov/topics/health.html
https://www.census.gov/topics/population/hispanic-origin.html
https://www.census.gov/topics/housing.html
https://www.census.gov/topics/income-poverty.html
https://www.census.gov/topics/international-trade.html
https://www.census.gov/topics/population.html
.......
0 голосов
/ 01 января 2019

Предполагается, что вы пытаетесь сохранить URL-адреса с сайта в файл CSV - по одному URL на строку.Сначала не используйте f, то есть для файла.Вы можете написать ссылку непосредственно в CSV, заключив ссылку в массив writer.writerow([link.get('href')]).Надеюсь, это поможет.В противном случае, пожалуйста, отредактируйте свой вопрос и добавьте больше деталей.

import csv
import requests
from bs4 import BeautifulSoup

j= [["Population and Housing Unit Estimates"]] # Title
k= [["Web Links"]] # Column Headings

example_listing='https://www.census.gov/programs-surveys/popest.html' #Source
r=requests.get(example_listing) #Grab page source html
html_page=r.text
soup=BeautifulSoup(html_page,'html.parser') #Build Beautiful Soup object to help parse the html
with open('HTMLList.csv','w', newline="") as f: #Choose what you want to grab
    writer=csv.writer(f, delimiter=' ',lineterminator='\r')
    writer.writerows(j)
    writer.writerows(k)
    for link in soup.find_all('a'):
        url = link.get('href')
        if url:
            writer.writerow([url])
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...