이 https://en.wikipedia.org/wiki/Web_scraping 페이지 를 스크래핑 한 다음 정보보기 섹션에서 19 개의 링크를 추출 하는 간단한 크롤러를 만들려고합니다 . 이 작업을 수행 할 수 있지만 19 개의 링크 각각에서 첫 번째 단락을 추출하려고합니다. 여기서 "작동"이 중지됩니다. 첫 페이지에서 동일한 단락을 가져오고 각 페이지에서 가져 오지 않습니다. 이것이 제가 지금까지 가지고있는 것입니다. 이 작업을 수행하는 데 더 나은 옵션이있을 수 있다는 것을 알고 있지만 BeautifulSoup 및 간단한 파이썬 코드를 고수하고 싶습니다.
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
url = 'https://en.wikipedia.org/wiki/Web_scraping'
data = requests.get('https://en.wikipedia.org/wiki/Web_scraping').text
soup = BeautifulSoup(data, 'html.parser')
def visit():
try:
p = soup.p
print(p.get_text())
except AttributeError:
print('<p> Tag was not found')
links_todo = []
links = soup.find('div', {'class': 'div-col'}).find_all('a')
for link in links:
if 'href' in link.attrs:
links_todo.append(urljoin(url, link.attrs['href']))
while links_todo:
url_to_visit = links_todo.pop()
print('Now visiting:', url_to_visit)
visit()
첫 번째 인쇄의 예
Now visiting: https://en.wikipedia.org/wiki/OpenSocial
Web scraping, web harvesting, or web data extraction is data scraping used for extracting data from websites. The web scraping software may directly access the World Wide Web using the Hypertext Transfer Protocol or a web browser. While web scraping can be done manually by a software user, the term typically refers to automated processes implemented using a bot or web crawler. It is a form of copying in which specific data is gathered and copied from the web, typically into a central local database or spreadsheet, for later retrieval or analysis.
의도 된 기능은 첫 번째 링크의 동일한 단락이 아닌 모든 새 링크에 대해 첫 번째 단락을 인쇄하는 것이어야합니다. 이 문제를 해결하려면 어떻게해야합니까? 또는 내가 놓친 것에 대한 팁. 저는 파이썬을 처음 접했기 때문에 작업하면서 개념을 배우고 있습니다.
코드 상단에서 정의 data
하고 soup
. 둘 다에 묶여 https://en.wikipedia.org/wiki/Web_scraping
있습니다.
전화 할 때마다 visit()
, 당신은에서 인쇄 soup
및 soup
변경하지 마십시오.
URL을에 전달해야합니다 ( visit()
예 :) visit(url_to_visit)
. visit
함수는 인수로 URL을 받아 사용하여 페이지를 방문해야 requests
하고, 반환 된 데이터에서 새 수프를 만든 다음 첫 번째 단락을 인쇄 할 수 있습니다.
내 원래 답변을 설명하는 코드를 추가하도록 편집되었습니다.
from urllib.parse import urljoin
import requests
from bs4 import BeautifulSoup
start_url = 'https://en.wikipedia.org/wiki/Web_scraping'
# Renamed this to start_url to make it clear that this is the source page
data = requests.get(start_url).text
soup = BeautifulSoup(data, 'html.parser')
def visit(new_url): # function now accepts a url as an argument
try:
new_data = requests.get(new_url).text # retrieve the text from the url
new_soup = BeautifulSoup(new_data, 'html.parser') # process the retrieved html in beautiful soup
p = new_soup.p
print(p.get_text())
except AttributeError:
print('<p> Tag was not found')
links_todo = []
links = soup.find('div', {'class': 'div-col'}).find_all('a')
for link in links:
if 'href' in link.attrs:
links_todo.append(urljoin(start_url, link.attrs['href']))
while links_todo:
url_to_visit = links_todo.pop()
print('Now visiting:', url_to_visit)
visit(url_to_visit) # here's where we pass each line to the visit() function
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다