Web Scraping with C++
https://www.scrapingbee.com/blog/web-scraping-c++/#building-the-web-scraper21
Jan 30 '23
Gumbo is interesting in that it gives the caller a treee where the nodes know their parent. This makes linearizing it, in dfs order, easy enough. Then we have an iterator. This opens up <algorthms>, but why stop there. There are a bunch of common queries that people do with html, what if we could build up some predicates and boolean logic with them. Thats when I had this https://github.com/beached/gumbo_pp It is not prod ready yet, but shows the interface we could have when we don’t just call C, but so what every other lang does when interacting with C
8
u/utf8decodeerror Jan 30 '23 edited Jan 30 '23
That's pretty lit. All my scrapers run as AWS Lambda functions in 10 min intervals so I usually write them in node or python - I have a framework I like and it's simple to maintain.
But I often end up with an s3 bucket full of thousands of html files that I have to parse later in the pipeline. This could definitely be a game changer in my biggest bottleneck. If the performance is considerably better than python's htmlsoup (I imagine so) I would def investigate using this in my tool chain.
Thanks for sharing!
13
Jan 30 '23 edited Jan 30 '23
No prob. I haven't compared this, but I remember comparing some Node stuff to C++ and the node was 300M ram idle and ~100ms to complete a task. C++ was 3M idle and <~10ms to complete. Both at about the same level of abstraction. I think we are too use to using C as is from C++ and not enough people are doing/sharing their higher level code. This is where other ecosystems are dominating, they don't accept C api's. Also, C++ could do very well in this space
7
u/arthurno1 Jan 31 '23 edited Jan 31 '23
works well for web scraping because of its ability to parse HTTP
When web scraping, it is not just ability to "parse HTTP", or you mean rather "HTML" (unless you are parsing HTTP protocol, which you are not), that maters. It is rather ability to quickly experiment while adjusting your parser for the site or html/xml at hand. C or C++, or any other compiled language are probably last languages I would ever consider to do web scraping with. If you use something like Lisp, Python or JS you would be still using libcurl, gumbo, xml2 & co, under the hood, but with much easier to use glue language. Especially Lisps are nice due to live environment. You could code your scraper without even reloading the document.
the extract_text function below extracts text from each node that is not a script or style tag.
Your text extraction is going through all the node in a gumbo vector looking for some string. People usually prefer to extract text based on a document structure.
In your case, as you have code, you will be making a new program for each HTML document you wish to parse, which itself is some unnecessary boilerplate, but you will also have to change your hardcoded strings in request for no good reason for every program too, and you can't even parse DOM structure since you are not building it out of gumbo. Performing any meaningful extraction from slightly complicated document will probably be rather pain in the a*s to work with, since you will have to write a lot of string manipulation to get it correct, compile every time, reload the document (from the internet as you have code it :)) and test it again.
With other words, what you suggest is not so good idea. Consider a language like Common Lisp with sbcl or Emacs Lisp with Emacs, where you can load a document, and then re-evaluate your functions and variables, re-code and re-evaluate them on the fly and test again on the same input without even reloading the original document from internet or the disk.
You can of course refactor everything, make request, and loading from the disk separated, keep the document in memory and ask user repeatedly for the input, in which case you end up with a simple interpreter sort of, so why bother to start with, instead of using one in form of Python, Node, Lisp?
But if you really believe there is a value in scraping text with C++, you should probably take a look at libxml2, there is a hack to use gumbo as html5 parser with libxml2 if you believe you need more speed or conformance.
That is just my opinion of course.
The str_replace function
What is wrong with std::string::replace?
Take also a look at std::string_view if you are not familiar with it since you don't seem to be using it.
4
u/daedalususedperl Jan 30 '23
I'm confused about this line, what does it do?
typedef size_t( * curl_write)(char * , size_t, size_t, std::string * );16
u/nysra Jan 30 '23
It's a type alias. It makes
curl_writethe type of a pointer to functions that returnsize_tand takes argumentschar*, size_t, size_t, std::string*. However it is terrible code because it's C code, in actual C++ you'd at the very least be usingusingand nevertypedefbut ideally properly put that entire thing into a concept and use templates.5
Jan 30 '23
Luckily the curl api has a void* data param, so we can actually wrap any callable into a type that exposes a std::function like interface with two methods, one to get the callback that calls the callable and one to get the volid *. The really nasty ones are the ones without that data param
1
u/joaquintides Boost author Jan 31 '23
How to do the trick is described here (and surely in many other places):
https://bannalia.blogspot.com/2016/07/passing-capturing-c-lambda-functions-as.html
1
Jan 31 '23
Thanks, nice writeup. I have a struct I wrote that just does it for me, it's common enough. I haven't explorer the case of doing actual thunking when there is no void*data pointer.
1
u/joaquintides Boost author Jan 31 '23 edited Jan 31 '23
Thunking can’t be done portably alas. Good candidate for a Boost library I’d say.
1
Jan 31 '23
Both of these are hard to do, yeah. Well this one isn't but too distracting from the code at hand. Not sure if a full library that does things to make C-apis less errorprone, or a core thing.
7
Jan 30 '23
using curl_write = size_t(*)( char * , size_t, size_t, std::string * );it defines a type alias for the callback used in curl, i assume. i didn't think string was part of that though.
2
4
Jan 30 '23
The equivalent in C++ would be:
using curl_write = std::function<std::size_t(char*, std::size_t, std::size_t, std::string*)>10
u/Tomik080 Jan 30 '23
It's definitely not an "equivalent". I'm all for simplifying things for teaching but in that specific case I think it's too farfetched.
using curl_write = std::size_t(*)(...)4
u/Breadfish64 Jan 31 '23 edited Feb 08 '23
To elaborate,
std::functionis wrapper around any invokeable type with right return and argument types. This is helpful for things like passing lambdas or member function pointers as callbacks, but the type erasure requires some runtime overhead which may or may not be acceptable.
Thestd::functionitself is 32 bytes on x64 libstd++ - the size of four function pointers, and it may also allocate extra memory to store the functor. Even if it doesn't allocate more memory, the constructor's side-effects still ruin some optimizations.
At the call-site, thestd::functionhas to check what it's storing and how to call it. A member function pointer for example would require thestd::functionto perform a vtable lookup using the first argument.
https://godbolt.org/z/K3oYjrjeM
4
2
u/aninteger Jan 31 '23
Well, this is all fine and good for simple sites but it's a bit more difficult with javascript. I wanted to build something on top of Okta's MFA portal site and ended up just using webkitgtk instead. It's ugly and GTK is awful but it got the job done.
1
2
1
u/pjmlp Jan 31 '23
While possible, the use of C APIs kind of proves the point why languages like C++ should not be directly plugged into the Internet, I have spotted a few places where pointer management can be nicely misused.
1
u/TheCrossX Cpp-Lang.net Maintainer Feb 06 '23
If I wanted to scrap data from a website I would use Puppeteer and Typescript, not C++.
0
Jan 30 '23
[deleted]
22
Jan 30 '23
ASM is too high of an abstraction for me. I manually write my machine code according to Intels totally not complicated instruction encoding.
10
0
0
Jan 30 '23
[deleted]
37
u/thisismyfavoritename Jan 30 '23
i hope you mean faster to develop?
Who uses it? People who care about performance
1
u/tavaren42 Jan 31 '23
Is the language performance really a bottleneck in scraping? (I am not asking rhetorically). Isn't the network latency that is the bottleneck?
3
u/thisismyfavoritename Jan 31 '23 edited Jan 31 '23
the network latency is absolutely the bottleneck but you still might want to utilize all the cores and easily share data in memory (e.g. in JS you'd use a worker pool which relies on IPC to share data AFAIK).
Even if it's dominated by I/O there is still some CPU processing involved to make requests and parse responses, and then you rarely will just dump that data somewhere.
Depending on what kind of processing you want to do on that data, C++ could be considered (or Rust)
13
Jan 30 '23
This is wild to me considering the intense mess that JS is in many ways. Easier? Sure. Faster? No way.
2
u/catcat202X Jan 30 '23
They likely meant faster to use, which is generally true since you can program it interactively (we have Cling, but..).
22
u/outofobscure Jan 30 '23
You might have heard about this company that does „web scraping“ called google?
12
6
2
u/serg06 Jan 30 '23 edited Jan 30 '23
Wrong sub to say this, but you're right. C++ is not the right tool for this job. TypeScript or Rust would fit better.
Nevertheless, it's good to see tutorials like this. I can't tell you how many times I've googled "how to do X in C++" and was unable to find any tutorials less than 20 years old.
6
Jan 30 '23 edited Jan 30 '23
I would question, have, why C++ is not great here. The answer usually comes back to no one has yet written the high level C++ libraries. Often once that is done, like any abstraction, we can do more and with less code/errors. The mistake I see so many do, is to just use C libraries as is.
2
u/plutoniator Jan 30 '23
Rust lol. Rust is great if you like writing rust but not if you want to end up with a working product in a reasonable amount of time. Maybe there’s a nice crate for it but god forbid you have to implement anything by yourself.
4
u/tavaren42 Jan 31 '23
While Rust is complex, it is not THAT complex. It is complex when compared to something with GC, but its not at all more complex than C++, imo, especially if you care about correctness. In fact, I have found it to be easier than C++ (mostly due to ADTs).
2
u/plutoniator Jan 31 '23 edited Jan 31 '23
It’s easier than C++ in that it has better tooling and compiler errors. If you take that away then Rust is much more complex than C++. It literally forces you to have complexity, just look at Bevy or Polars or Yew. Everything written in rust has a dozen different layers of indirection, macros everywhere, needing to make a bunch of structs and enums to call a function (or some sort of custom default arguments implementation). A much more fair comparison would be Rust vs Carbon, and it doesn’t look good for rust.
2
u/serg06 Jan 30 '23
Maybe there’s a nice crate for it
That's half the reason I suggested it lol. It has high level libraries for everything. I bet downloading a website and parsing the HTML is only a few lines.
17
u/[deleted] Jan 31 '23
I love C++, but I prefer to do this kind of things using Python. (Despite I hate Python)