검색 양식을 작성하고 검색하기 위해 웹 스크래핑?
-
19-09-2019 - |
문제
검색 양식에 항목을 입력하고 결과에서 일치를 추출하는 작업을 "자동화"할 수 있는지 궁금합니다. 예를 들어, Doi (Digital Object Identifier)를 얻고 싶은 저널 기사 목록이 있습니다. 이를 위해 수동으로 저널 기사 검색 페이지로 이동합니다 (예 : http://pubs.acs.org/search/advanced), 저자/제목/볼륨 (등)을 입력 한 다음 반환 된 결과 목록에서 기사를 찾아서 DOI를 골라 내 참조 목록에 붙여 넣습니다. 데이터 분석에 R과 Python을 정기적으로 사용하지만 (RCURL에 대한 게시물에서 영감을 얻었지만) 웹 프로토콜에 대해 잘 모릅니다 ... 예를 들어 Python의 BeautifulSoup과 같은 것을 사용하는 것과 같은 것이 가능합니까?). 이 작업과 원격으로 비슷한 일을하는 것에 대한 좋은 참조가 있습니까? 저는 웹 스크래핑과 웹 스크래핑을위한 도구에 대해 배우는 데 관심이 많습니다.
해결책
아름다운 수프는 웹 페이지를 구문 분석하기에 좋습니다. 그것은 당신이하고 싶은 것의 절반입니다. Python, Perl 및 Ruby는 모두 Mechanize의 버전을 가지고 있으며 다른 절반입니다.
http://wwwsearch.sourceforge.net/mechanize/
기계화 브라우저를 제어하자 :
# Follow a link
browser.follow_link(link_node)
# Submit a form
browser.select_form(name="search")
browser["authors"] = ["author #1", "author #2"]
browser["volume"] = "any"
search_response = br.submit()
기계화와 아름다운 수프를 사용하면 좋은 출발이 있습니다. 이 빠른 루비 스크래핑 안내서에 사용 된 바와 같이 내가 고려해야 할 추가 도구 중 하나는 FireBug입니다.
http://www.igvita.com/2007/02/04/ruby-screen-scraper-in-60-seconds/
Firebug는 문서를 구문 분석 용 XPaths 건설 속도를 높이고 심각한 시간을 절약 할 수 있습니다.
행운을 빕니다!
다른 팁
파이썬 코드 : 검색 양식의 경우.
# import
from selenium import webdriver
from selenium.common.exceptions import TimeoutException
from selenium.webdriver.support.ui import WebDriverWait # available since 2.4.0
from selenium.webdriver.support import expected_conditions as EC # available since 2.26.0
# Create a new instance of the Firefox driver
driver = webdriver.Firefox()
# go to the google home page
driver.get("http://www.google.com")
# the page is ajaxy so the title is originally this:
print driver.title
# find the element that's name attribute is q (the google search box)
inputElement = driver.find_element_by_name("q")
# type in the search
inputElement.send_keys("cheese!")
# submit the form (although google automatically searches now without submitting)
inputElement.submit()
try:
# we have to wait for the page to refresh, the last thing that seems to be updated is the title
WebDriverWait(driver, 10).until(EC.title_contains("cheese!"))
# You should see "cheese! - Google Search"
print driver.title
finally:
driver.quit()
WebRequest req = WebRequest.Create("http://www.URLacceptingPOSTparams.com");
req.Proxy = null;
req.Method = "POST";
req.ContentType = "application/x-www-form-urlencoded";
//
// add POST data
string reqString = "searchtextbox=webclient&searchmode=simple&OtherParam=???";
byte[] reqData = Encoding.UTF8.GetBytes (reqString);
req.ContentLength = reqData.Length;
//
// send request
using (Stream reqStream = req.GetRequestStream())
reqStream.Write (reqData, 0, reqData.Length);
string response;
//
// retrieve response
using (WebResponse res = req.GetResponse())
using (Stream resSteam = res.GetResponseStream())
using (StreamReader sr = new StreamReader (resSteam))
response = sr.ReadToEnd();
// use a regular expression to break apart response
// OR you could load the HTML response page as a DOM
(Joe Albahri의 "C# in a nutshell"에서 적응 함)
웹 스크래핑을위한 많은 도구가 있습니다. Imacros라는 좋은 Firefox 플러그인이 있습니다. 그것은 훌륭하게 작동하며 프로그래밍 지식이 전혀 필요하지 않습니다. 무료 버전은 여기에서 다운로드 할 수 있습니다.https://addons.mozilla.org/en-us/firefox/addon/imacros-for-firefox/Imacros의 가장 좋은 점은 몇 분 안에 시작할 수 있고 Bash 명령 줄에서 시작할 수 있으며 Bash 스크립트 내에서 호출 할 수도 있다는 것입니다.
보다 진보 된 단계는 셀레늄 웹 드라이브입니다. 내가 셀레늄을 선택한 이유는 초보자에게 좋은 방법으로 기록되어 있기 때문입니다. 다음을 읽습니다 페이지:
곧 당신을 올릴 것입니다. Selenium은 Java, Python, PHP, C를 지원하므로 이러한 언어에 익숙하다면 필요한 모든 명령에 익숙 할 것입니다. 브라우저가 열리므로 셀레늄의 웹 드라이브 변형을 선호하여 필드와 출력을 확인할 수 있습니다. WebDrive를 사용하여 스크립트를 설정 한 후 스크립트를 IDE로 쉽게 마이그레이션하여 헤드리스를 실행할 수 있습니다.
셀레늄을 설치하려면 명령을 입력하여 할 수 있습니다.
sudo easy_install selenium
이것은 의존성과 필요한 모든 것을 처리합니다.
대화식으로 스크립트를 실행하려면 터미널을 열고
python
Python 프롬프트가 표시되며 >>> 명령을 입력 할 수 있습니다.
다음은 터미널에 붙여 넣을 수있는 샘플 코드입니다. Google은 Cheeses라는 단어를 검색합니다.
package org.openqa.selenium.example;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.firefox.FirefoxDriver;
import org.openqa.selenium.support.ui.ExpectedCondition;
import org.openqa.selenium.support.ui.WebDriverWait;
public class Selenium2Example {
public static void main(String[] args) {
// Create a new instance of the Firefox driver
// Notice that the remainder of the code relies on the interface,
// not the implementation.
WebDriver driver = new FirefoxDriver();
// And now use this to visit Google
driver.get("http://www.google.com");
// Alternatively the same thing can be done like this
// driver.navigate().to("http://www.google.com");
// Find the text input element by its name
WebElement element = driver.findElement(By.name("q"));
// Enter something to search for
element.sendKeys("Cheese!");
// Now submit the form. WebDriver will find the form for us from the element
element.submit();
// Check the title of the page
System.out.println("Page title is: " + driver.getTitle());
// Google's search is rendered dynamically with JavaScript.
// Wait for the page to load, timeout after 10 seconds
(new WebDriverWait(driver, 10)).until(new ExpectedCondition<Boolean>() {
public Boolean apply(WebDriver d) {
return d.getTitle().toLowerCase().startsWith("cheese!");
}
});
// Should see: "cheese! - Google Search"
System.out.println("Page title is: " + driver.getTitle());
//Close the browser
driver.quit();
}}
이것이 당신에게 헤드 스타트를 줄 수 있기를 바랍니다.
건배 :)