programing

Python을 사용한 웹 스크래핑

goodjava 2023. 6. 4. 22:18

Python을 사용한 웹 스크래핑

저는 웹사이트에서 매일 일출/일몰 시간을 얻고 싶습니다.파이썬으로 웹 콘텐츠를 긁어낼 수 있습니까?사용되는 모듈은 무엇입니까?사용 가능한 튜토리얼이 있습니까?

urllib2를 멋진 BeautifulSoup 라이브러리와 함께 사용합니다.

import urllib2
from BeautifulSoup import BeautifulSoup
# or if you're using BeautifulSoup4:
# from bs4 import BeautifulSoup

soup = BeautifulSoup(urllib2.urlopen('http://example.com').read())

for row in soup('table', {'class': 'spad'})[0].tbody('tr'):
    tds = row('td')
    print tds[0].string, tds[1].string
    # will print date and sunrise

저는 스크레이피를 정말 추천합니다.

삭제된 답변에서 인용:

  • 스크레이피 크롤링은 기계화보다 빠릅니다. 왜냐하면 ( 트위스트 위에서) 비동기 작업을 사용하기 때문입니다.
  • Scrapy는 libxml2 위에서 (x)html 구문 분석을 더 빠르고 효율적으로 지원합니다.
  • Scrapy는 완전한 유니코드, 리디렉션, 압축된 응답, 홀수 인코딩, 통합된 http 캐시 등을 처리하는 성숙한 프레임워크입니다.
  • Scrapy에 빠지면 5분 이내에 거미를 작성하여 이미지를 다운로드하고 섬네일을 생성하며 추출된 데이터를 직접 csv 또는 json으로 내보낼 수 있습니다.

저는 제 웹스크래핑 작업의 스크립트를 이 비트 버킷 라이브러리에 수집했습니다.

사례에 대한 예제 스크립트:

from webscraping import download, xpath
D = download.Download()

html = D.get('http://example.com')
for row in xpath.search(html, '//table[@class="spad"]/tbody/tr'):
    cols = xpath.search(row, '/td')
    print 'Sunrise: %s, Sunset: %s' % (cols[1], cols[2])

출력:

Sunrise: 08:39, Sunset: 16:08
Sunrise: 08:39, Sunset: 16:09
Sunrise: 08:39, Sunset: 16:10
Sunrise: 08:40, Sunset: 16:10
Sunrise: 08:40, Sunset: 16:11
Sunrise: 08:40, Sunset: 16:12
Sunrise: 08:40, Sunset: 16:13

저는 파이쿼리를 확인하는 것을 강력히 추천합니다.그것은 jquery와 같은 (일명 css와 같은) 구문을 사용하여 그 배경에서 온 사람들이 정말 쉽게 할 수 있도록 합니다.

귀하의 경우 다음과 같습니다.

from pyquery import *

html = PyQuery(url='http://www.example.com/')
trs = html('table.spad tbody tr')

for tr in trs:
  tds = tr.getchildren()
  print tds[1].text, tds[2].text

출력:

5:16 AM 9:28 PM
5:15 AM 9:30 PM
5:13 AM 9:31 PM
5:12 AM 9:33 PM
5:11 AM 9:34 PM
5:10 AM 9:35 PM
5:09 AM 9:37 PM

urllib2를 사용하여 HTTP 요청을 수행하면 웹 콘텐츠가 생성됩니다.

다음과 같이 얻을 수 있습니다.

import urllib2
response = urllib2.urlopen('http://example.com')
html = response.read()

Beautiful Soup은 스크린 스크래핑에 좋은 파이썬 HTML 파서입니다.

특히, 여기 HTML 문서를 구문 분석하는 방법에 대한 튜토리얼이 있습니다.

행운을 빕니다.

Scratchmark(url 찾기 - py2)와 httlib2(이미지 다운로드 - py2+3)의 조합을 사용합니다.scrapemark.py 에는 500줄의 코드가 있지만 정규식을 사용하기 때문에 그렇게 빠르지 않을 수도 있습니다. 테스트하지 않았습니다.

웹 사이트 스크랩 예제:

import sys
from pprint import pprint
from scrapemark import scrape

pprint(scrape("""
    <table class="spad">
        <tbody>
            {*
                <tr>
                    <td>{{[].day}}</td>
                    <td>{{[].sunrise}}</td>
                    <td>{{[].sunset}}</td>
                    {# ... #}
                </tr>
            *}
        </tbody>
    </table>
""", url=sys.argv[1] ))

용도:

python2 sunscraper.py http://www.example.com/

결과:

[{'day': u'1. Dez 2012', 'sunrise': u'08:18', 'sunset': u'16:10'},
 {'day': u'2. Dez 2012', 'sunrise': u'08:19', 'sunset': u'16:10'},
 {'day': u'3. Dez 2012', 'sunrise': u'08:21', 'sunset': u'16:09'},
 {'day': u'4. Dez 2012', 'sunrise': u'08:22', 'sunset': u'16:09'},
 {'day': u'5. Dez 2012', 'sunrise': u'08:23', 'sunset': u'16:08'},
 {'day': u'6. Dez 2012', 'sunrise': u'08:25', 'sunset': u'16:08'},
 {'day': u'7. Dez 2012', 'sunrise': u'08:26', 'sunset': u'16:07'}]

를 사용하여 생활을 보다 쉽게 할 수 있습니다.CSS Selectors

파티에 늦게 온 건 알지만 좋은 제안이 있어요.

용사를 합니다.BeautifulSoup된 바와 같이 이미제었다니습되를 하는 것을 합니다. 차라리 사용하고 싶습니다.CSS SelectorsHTMLHTML

import urllib2
from bs4 import BeautifulSoup

main_url = "http://www.example.com"

main_page_html  = tryAgain(main_url)
main_page_soup = BeautifulSoup(main_page_html)

# Scrape all TDs from TRs inside Table
for tr in main_page_soup.select("table.class_of_table"):
   for td in tr.select("td#id"):
       print(td.text)
       # For acnhors inside TD
       print(td.select("a")[0].text)
       # Value of Href attribute
       print(td.select("a")[0]["href"])

# This is method that scrape URL and if it doesnt get scraped, waits for 20 seconds and then tries again. (I use it because my internet connection sometimes get disconnects)
def tryAgain(passed_url):
    try:
        page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
        return page
    except Exception:
        while 1:
            print("Trying again the URL:")
            print(passed_url)
            try:
                page  = requests.get(passed_url,headers = random.choice(header), timeout = timeout_time).text
                print("-------------------------------------")
                print("---- URL was successfully scraped ---")
                print("-------------------------------------")
                return page
            except Exception:
                time.sleep(20)
                continue 

특정 범주에서 항목의 이름을 얻는 것을 생각하면 CSS 선택기를 사용하여 해당 범주의 클래스 이름을 지정하면 됩니다.

import requests ; from bs4 import BeautifulSoup

soup = BeautifulSoup(requests.get('https://www.flipkart.com/').text, "lxml")
for link in soup.select('div._2kSfQ4'):
    print(link.text)

다음은 부분 검색 결과입니다.

Puma, USPA, Adidas & moreUp to 70% OffMen's Shoes
Shirts, T-Shirts...Under ₹599For Men
Nike, UCB, Adidas & moreUnder ₹999Men's Sandals, Slippers
Philips & moreStarting ₹99LED Bulbs & Emergency Lights

여기 간단한 웹 크롤러가 있습니다, 저는 BeautifulSoup을 사용했고 우리는 클래스 이름이 _3NFO0d인 모든 링크(앵커)를 검색할 것입니다.저는 Flipkar.com 을 사용했고, 그것은 온라인 소매점입니다.

import requests
from bs4 import BeautifulSoup
def crawl_flipkart():
    url = 'https://www.flipkart.com/'
    source_code = requests.get(url)
    plain_text = source_code.text
    soup = BeautifulSoup(plain_text, "lxml")
    for link in soup.findAll('a', {'class': '_3NFO0d'}):
        href = link.get('href')
        print(href)

crawl_flipkart()

Python은 웹을 긁어내는 좋은 옵션을 가지고 있습니다.골격이 있는 가장 좋은 것은 스크래피입니다.초보자에게는 조금 까다로울 수 있으니, 여기 약간의 도움이 있습니다.
.7까지 합니다). 3.5 "python" (2.7 "python").
콘다에 환경을 조성합니다(제가 이렇게 했습니다).
위치에 스크레이피를 설치하고 그 위치에서 실행합니다.
4. Scrapy shell코드를 테스트할 수 있는 대화형 인터페이스를 제공합니다.
5. Scrapy startproject projectname프레임워크를 만듭니다.
6. Scrapy genspider spidername거미를 만들 것입니다.원하는 만큼 거미를 만들 수 있습니다.이 작업을 수행하는 동안 사용자가 프로젝트 디렉토리 안에 있는지 확인합니다.


요청과 아름다운 수프를 사용하는 것이 더 쉽습니다.시작하기 전에 한 시간 동안 문서를 검토할 시간을 주면 대부분의 의구심을 해소할 수 있습니다. BS4는 선택할 수 있는 광범위한 파서를 제공합니다.사용하다user-agent그리고.sleep하므로 BS4는 ab.tag를 사용합니다.variable[0]실행 중인 js가 있으면 요청 및 bs4를 사용하여 직접 스크랩할 수 없습니다.api 링크를 얻은 다음 JSON을 구문 분석하여 필요한 정보를 얻거나 시도할 수 있습니다.selenium.

언급URL : https://stackoverflow.com/questions/2081586/web-scraping-with-python