【问题标题】:automatic crawling using selenium使用 selenium 自动爬取
【发布时间】:2019-07-14 00:48:27
【问题描述】:
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC

OUTPUT_FILE_NAME = 'output0.txt'
driver = webdriver.Chrome()
wait = WebDriverWait(driver, 10)

def get_text():
    driver.get("http://law.go.kr/precSc.do?tabMenuId=tab67")
    elem = wait.until(EC.visibility_of_element_located((By.CSS_SELECTOR, "#viewHeightDiv > 
table > tbody > "
                                                                 "tr:nth-child(1) > 
td.s_tit > a")))

    title = elem.text.strip().split(" ")[0]
    elem.click()

    wait.until(EC.text_to_be_present_in_element((By.CSS_SELECTOR, "#viewwrapCenter h2"), 
title))
    content = driver.find_element_by_css_selector("#viewwrapCenter").text
    return content

def main():
    open_output_file = open(OUTPUT_FILE_NAME, 'w')
    result_text = get_text()
    open_output_file.write(result_text)
    open_output_file.close()

main()

基于此代码,我想抓取此网站。 就像从原始 url selenium 进入第一个链接并将文本保存到 txt 文件一样,它会返回到原始 url 并进入第二个链接并继续 但问题是第一个链接的 css_selector 值是 #viewHeightDiv > table > tbody > tr:nth-child(1) > td.s_tit > a 和第二个链接是 #viewHeightDiv > table > tbody > tr:nth-child(3) > td.s_tit > 他们之间唯一的区别是孩子后面的数字,似乎没有规则,它像 1,3,5,9,...所以我卡在这里...

【问题讨论】:

    标签: python selenium web web-crawler


    【解决方案1】:

    你可以像这样使用定位器:

    td.s_tit > a
    

    【讨论】:

      【解决方案2】:

      要抓取所有不需要 Selenium 的帖子。您可以使用 Requests 和 BeautifulSoup 库来完成所有操作:

      import requests
      from bs4 import BeautifulSoup
      
      if __name__ == '__main__':
      
          # Using request get 50 items from first page. pg=1 is page number, outmax=50 items per page
          response = requests.post(
              "http://law.go.kr/precScListR.do?q=*&section=evtNm&outmax=50&pg=1&fsort=21,10,30&precSeq=0&dtlYn=N")
      
          # Parse html using BeautifulSoup
          page = BeautifulSoup(response.text, "html.parser")
      
          # Find "go to last page" element and get "onclick" attribute, inside "onlick" attribute parse last page number
          # for "outmax=50" (used before)
          onclick = str(page.select(".paging > a:last-child")[0].attrs["onclick"])
          last_page_number = int(''.join([n for n in onclick if n.isdigit()]))
      
          # To test uncomment code below to get items only from first page
          # last_page_number = 1
      
          # Go through all pages and collect posts numbers in items
          items = []
          for i in range(1, last_page_number + 1):
              if i>1:
                  # Go to next page
                  response = requests.post(
                      "http://law.go.kr/precScListR.do?q=*&section=evtNm&outmax=100&pg=%d&fsort=21,10,30&precSeq=0&dtlYn=N" % i)
      
              # Get all links
              links = page.select("#viewHeightDiv .s_tit a")
              # Loop all links and collect post numbers
              for link in links:
                  # Parse post number from "onclick" attribute
                  items.append(''.join([n for n in link.attrs["onclick"] if n.isdigit()]))
      
          # Open all posts and collect in posts dictionary with keys: number, url and text
          posts = []
          for item in items:
              url = "http://law.go.kr/precInfoR.do?precSeq=%s&vSct=*" % item
              response = requests.get(url)
              t = BeautifulSoup(response.text, "html.parser").find('div', attrs={'id': 'contentBody'}).text
              posts.append({'number': item, 'url': url, 'text': t})
      

      要保存到文件,请将代码的最后一部分更改为下面,其中/yourfullpath/ 替换为您的路径,例如“C://files/”或“/Users/myuser/files/”:

      # Open all posts and collect in posts dictionary with keys: number, url and text
      posts = []
      for item in items:
          url = "http://law.go.kr/precInfoR.do?precSeq=%s&vSct=*" % item
          response = requests.get(url)
          parsed = BeautifulSoup(response.text, "html.parser")
          text = parsed.find('div', attrs={'id': 'contentBody'}).text
          title = parsed.select_one("h2").text
          posts.append({'number': item, 'url': url, 'text': text, 'title': title})
      
          with open('/yourfullpath/' + title + '.text', 'w') as f:
              f.write(text)
      

      【讨论】:

      • 我仍然很困惑...以及如何将所有文本放入一个txt文件...使用'a'模式?在文本文件上?没有真正理解这段代码,我迷路了..
      • 那么这段代码是否会刮掉所有链接的所有正文?当我看不到代码是否工作时..需要更多的研究或解释。
      • @KwanheeHwang 是的,代码将从所有内容中抓取所有内容并存储帖子地图。您可以稍后使用它来写入文件或其他任何内容。代码只是通过使用 url 发布请求来获取数据。阅读一些有关 requests 库和 Web 工作原理的信息,您就会明白。
      • 您是如何获得响应网址的?加上我试图为每个 itme 的 t 创建 txt 文件,但它只创建一个文件...
      • @KwanheeHwang 回复并快乐
      猜你喜欢
      • 2019-07-19
      • 1970-01-01
      • 2015-02-19
      • 1970-01-01
      • 1970-01-01
      • 2018-06-17
      • 2016-12-12
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多